Initial commit

This commit is contained in:
Kwesi Banson Jnr
2026-09-09 09:50:06 +00:00
commit c7f93a7dc1
8369 changed files with 517137 additions and 0 deletions

View File

@@ -0,0 +1,146 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Exception;
use Illuminate\Support\Facades\Crypt;
class SyncSubscriptionsServices extends Command
{
// The command name to run in the terminal
protected $signature = 'subscriptions:sync';
protected $description = 'Incremental ETL process to normalize and warehouse subscription data';
public function handle()
{
$services = DB::table('subscription_services')->get();
if ($services->isEmpty()) {
$this->info('No subscription services configured. Exiting.');
return;
}
foreach ($services as $service) {
$this->info("Starting sync for Service: {$service->name}");
// 1. Define High Water Mark (Fallback to an old date for the very first run)
$lastSync = $service->last_synced_at ?? '2000-01-01 00:00:00';
// 2. Capture the exact time we are starting THIS sync
$syncStartTime = now();
// 3. Inject Dynamic Connection
try {
Config::set('database.connections.service_dynamic', [
'driver' => 'mysql',
'host' => $service->db_host,
'port' => $service->db_port,
'database' => $service->db_name,
'username' => $service->db_user,
// 'password' => decrypt($service->db_password),
'password' => Crypt::decryptString($service->db_password),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
]);
DB::purge('service_dynamic');
$dynamicDb = DB::connection('service_dynamic');
// Quick ping to verify credentials before running massive queries
$dynamicDb->getPdo();
} catch (Exception $e) {
$this->error("Connection failed for {$service->name}: " . $e->getMessage());
continue; // Skip to the next service on failure
}
// 4. Extract & Transform incrementally based on schema type
try {
if ($service->schema_type === 'type_a') {
$this->syncTypeA($dynamicDb, $service->id, $lastSync);
} elseif ($service->schema_type === 'type_b') {
$this->syncTypeB($dynamicDb, $service->id, $lastSync);
} else {
$this->warn("Unknown schema type '{$service->schema_type}' for {$service->name}. Skipping.");
continue;
}
// 5. Update the High Water Mark in the Hub database on success
DB::table('subscription_services')
->where('id', $service->id)
->update(['last_synced_at' => $syncStartTime]);
$this->info("Successfully synced {$service->name} up to {$syncStartTime}");
} catch (Exception $e) {
// If it fails, the last_synced_at is not updated.
// The next run will safely pick up from the previous successful mark.
$this->error("Failed syncing {$service->name}: " . $e->getMessage());
}
}
$this->newLine();
$this->info('ETL Synchronization complete.');
}
/**
* Mapper for Schema Type A (msisdn, is_active, updated_at)
*/
private function syncTypeA($db, $serviceId, $lastSync)
{
$db->table('subscriptions')
//->where('updated_at', '>=', $lastSync)
->orderBy('id')
->chunk(1000, function ($subscriptions) use ($serviceId) {
$normalizedData = [];
foreach ($subscriptions as $subscription) {
$normalizedData[] = [
'service_id' => $serviceId,
'phone_number' => $subscription->msisdn,
'content_name' => $subscription->content ?? 'Standard Bundle',
'status' => ($subscription->status == 'ON') ? 'active' : 'inactive',
'join_date' => $subscription->created_at,
'updated_at' => now(),
'created_at' => now(),
];
}
// Bulk Upsert: Insert if new, Update if phone_number+service_id exists
DB::table('unified_subscribers')->upsert(
$normalizedData,
['service_id', 'phone_number', 'content_name'],
['status', 'updated_at']
);
});
}
/**
* Mapper for Schema Type B (cell_number, sub_state, updated_on)
*/
private function syncTypeB($db, $serviceId, $lastSync)
{
$db->table('subscribers')
->where('updated_on', '>=', $lastSync)
->orderBy('sub_id')
->chunk(1000, function ($subs) use ($serviceId) {
$normalizedData = [];
foreach ($subs as $sub) {
$normalizedData[] = [
'service_id' => $serviceId,
'phone_number' => $sub->cell_number,
'status' => strtolower($sub->sub_state), // standardizes to 'active' or 'inactive'
'join_date' => $sub->date_joined,
'updated_at' => now(),
'created_at' => now(),
];
}
DB::table('unified_subscribers')->upsert(
$normalizedData,
['service_id', 'phone_number'],
['status', 'updated_at']
);
});
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ConfirmsPasswords;
class ConfirmPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Confirm Password Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password confirmations and
| uses a simple trait to include the behavior. You're free to explore
| this trait and override any functions that require customization.
|
*/
use ConfirmsPasswords;
/**
* Where to redirect users when the intended url fails.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class ForgotPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/
use SendsPasswordResetEmails;
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('auth')->only('logout');
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* @var string
*/
protected $redirectTo = '/home';
}

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;
class VerificationController extends Controller
{
/*
|--------------------------------------------------------------------------
| Email Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
use VerifiesEmails;
/**
* Where to redirect users after verification.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('signed')->only('verify');
$this->middleware('throttle:6,1')->only('verify', 'resend');
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace App\Http\Controllers;
use Session;
use App\Models;
use Illuminate\Http\Request;
class CommentsController extends Controller
{
public function index(){
$user_id = \Auth::user()->id;
$result = Models\Comment::with('projectStatus')
->where('assignee_id', $user_id)
->orderBy('project_id', 'DESC')
->get();
$data = [
'page_title' => 'Projects Status List',
'project_statuses' => $result
];
return view('comments.index', $data);
}
public function add_comment($id){
$result = Models\ProjectStatus::with('comments', 'project')->where('id', $id)->firstOrFail();
// dd($result);
$data = [
'page_title' => 'Projects Status Comment',
'project_arr' => $result
];
// dump($data);
return view('comments.create', $data);
}
public function store(Request $request) {
// Save a new post
$this->validate($request, [
'description' => 'required',
'status' => 'required',
'project_id' => 'required',
'assignee_id' => 'required'
]);
$project_status_arr = $request->except('_token');
$result = Models\ProjectStatus::create($project_status_arr);
Session::flash('success_message', 'Project status added successfully!');
return redirect(url('project-status'));
}
public function show($id) {
// Show a specific post
}
public function edit($id) {
// Show form to edit a post
}
public function update(Request $request, $id) {
// Update a specific post
return redirect(url('project-status'));
}
public function destroy($id) {
// Delete a specific post
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, ValidatesRequests;
}

View File

@@ -0,0 +1,81 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DashboardController extends Controller
{
public function index(){
// dd('public insanity');
return view('dashboard.index');
}
public function getDashboardStats()
{
$stats = DB::table('unified_subscribers')
->select('service_id', DB::raw('count(*) as total'), DB::raw('SUM(status = "active") as active_count'))
->groupBy('service_id')
->get();
return response()->json($stats);
}
public function getStats()
{
// Query the unified warehouse table, grouping by the service configuration
$stats = DB::table('subscription_services as s')
->leftJoin('unified_subscribers as u', 's.id', '=', 'u.service_id')
->select(
's.id',
's.name',
DB::raw('COUNT(u.id) as total_subscribers'),
// Use CASE WHEN for strict SQL compatibility
DB::raw('SUM(CASE WHEN u.status = "active" THEN 1 ELSE 0 END) as active_subscribers')
)
->groupBy('s.id', 's.name')
->get();
// Calculate a quick summary for the top-level overview
$grandTotal = $stats->sum('total_subscribers');
$grandActive = $stats->sum('active_subscribers');
return response()->json([
'summary' => [
'total' => $grandTotal,
'active' => $grandActive,
'inactive' => $grandTotal - $grandActive
],
'services' => $stats
]);
}
// app/Http/Controllers/DashboardController.php
// app/Http/Controllers/DashboardController.php
public function details(Request $request, $id)
{
$service = DB::table('subscription_services')->where('id', $id)->first();
if (!$service) {
abort(404, 'Service not found.');
}
$search = $request->input('search');
$subscribers = DB::table('unified_subscribers')
->where('service_id', $id)
->when($search, function($query, $search) {
$query->where(function($q) use ($search) {
$q->where('phone_number', 'like', "%{$search}%")
->orWhere('content_name', 'like', "%{$search}%")
->orWhere('status', 'like', "%{$search}%")
->orWhere('join_date', 'like', "%{$search}%");
});
})
->orderBy('updated_at', 'desc')
->paginate(15);
return view('dashboard.details', compact('service', 'subscribers'));
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Config;
use Exception;
class SubscriptionServiceController extends Controller
{
public function create()
{
return view('services.create');
}
public function store(Request $request)
{
// 1. Validate the incoming data
$validated = $request->validate([
'name' => 'required|string|max:255',
'schema_type' => 'required|string|in:type_a,type_b', // Restrict to known schema mappers
'db_host' => 'required|string|max:255',
'db_port' => 'required|integer|min:1|max:65535',
'db_name' => 'required|string|max:255',
'db_user' => 'required|string|max:255',
'db_password' => 'required|string', // Plain text from form
]);
// 2. Insert into the database with encryption
DB::table('subscription_services')->insert([
'name' => $validated['name'],
'schema_type' => $validated['schema_type'],
'db_host' => $validated['db_host'],
'db_port' => $validated['db_port'],
'db_name' => $validated['db_name'],
'db_user' => $validated['db_user'],
'db_password' => Crypt::encryptString($validated['db_password']), // Secure encryption
'last_synced_at' => null, // Will be populated on first ETL run
'created_at' => now(),
'updated_at' => now(),
]);
// 3. Redirect back with a success message
return redirect()
->route('services.create')
->with('success', 'Subscription service added successfully.');
}
public function testConnection(Request $request)
{
// Validate the incoming AJAX payload
$request->validate([
'db_host' => 'required|string',
'db_port' => 'required|integer',
'db_name' => 'required|string',
'db_user' => 'required|string',
'db_password' => 'required|string',
]);
try {
// 1. Set a temporary dynamic configuration
Config::set('database.connections.test_dynamic', [
'driver' => 'mysql',
'host' => $request->db_host,
'port' => $request->db_port,
'database' => $request->db_name,
'username' => $request->db_user,
'password' => $request->db_password,
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
]);
DB::purge('test_dynamic');
// 2. Attempt to resolve the PDO instance to verify the connection
DB::connection('test_dynamic')->getPdo();
// 3. Return success if no exception was thrown
return response()->json([
'status' => 'success',
'message' => 'Connection established successfully.'
]);
} catch (Exception $e) {
return response()->json([
'status' => 'error',
'message' => 'Connection failed: ' . $e->getMessage()
], 400); // 400 Bad Request triggers the AJAX error block
}
}
}

23
app/Models/Comment.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Comment extends Model
{
protected $guarded = [
'id'
];
public function userInfo(): HasOne
{
return $this->hasOne(User::class);
}
public function projectStatus(): BelongsTo
{
return $this->belongsTo(ProjectStatus::class);
}
}

31
app/Models/Project.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Project extends Model
{
protected $guarded = [
'id'
];
// public function userInfo()
// {
// return $this->hasMany('App\Models\User', 'org_id', 'id');
// }
// public function phone(): HasOne
// {
// return $this->hasOne(Phone::class);
// }
public function userInfo(): HasMany
{
return $this->hasMany(User::class);
}
public function statusInfo(): HasMany
{
return $this->hasMany(ProjectStatus::class);
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class ProjectStatus extends Model
{
protected $guarded = [
'id'
];
public function project(): BelongsTo
{
return $this->belongsTo(Project::class);
}
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
}

48
app/Models/User.php Normal file
View File

@@ -0,0 +1,48 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
//
}
public function boot(): void
{
Paginator::useBootstrapFive();
}
}