feat(profile,publications): integrate working Google Scholar import flow and unified faculty profile system

This commit is contained in:
Harshil Vora
2025-10-18 02:53:32 -07:00
parent 8fe0ef8112
commit ba28588e38
19 changed files with 915 additions and 139 deletions

View File

@@ -73,8 +73,14 @@ class FacultyController extends Controller
public function viewPublicationsResponses()
{
$departments = Department::all();
return view('pages.publications.index', compact('departments'));
$user = auth()->user();
\Log::info('FacultyController: scholar_url = ' . ($user->scholar_url ?? 'NULL'));
return view('pages.publications.index', [
'scholarUrl' => $user->scholar_url,
]);
}
public function BooksPublishedForm()
@@ -536,7 +542,7 @@ class FacultyController extends Controller
'offered_by' => 'required|string',
'start_date' => 'required|date',
'end_date' => 'required|date',
'num_days' => 'required|integer',
'num_days' => 'required|integer',
'proof' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,docx,zip',
]);
@@ -615,7 +621,7 @@ class FacultyController extends Controller
}
// dd($proofFilePath);
// Save the response to the database
Patent::create([
'department_id' => auth()->user()->department->id,

View File

@@ -0,0 +1,120 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\FacultyProfile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
class FacultyProfileController extends Controller
{
/**
* Show logged-in user's faculty profile.
*/
public function index()
{
$user = Auth::user();
$profile = FacultyProfile::firstOrCreate(
['user_id' => $user->id],
[
'name' => $user->name ?? '',
'email' => $user->email ?? '',
'phone_number' => '',
'vidhvan_id' => '',
'google_scholar_id' => '',
'linkedin_id' => '',
'designation' => '',
'salutation' => '',
'qualification' => '',
'address' => '',
'employee_id' => '',
'department_name' => '',
'programme_name' => '',
'date_of_joining' => now()->toDateString(),
]
);
return view('profile.index', compact('user', 'profile'));
}
/**
* Show the edit form for faculty profile.
*/
public function edit()
{
$user = Auth::user();
$profile = FacultyProfile::where('user_id', $user->id)->firstOrFail();
return view('profile.edit', compact('profile'));
}
/**
* Update faculty profile.
*/
public function update(Request $request)
{
$user = Auth::user();
$profile = FacultyProfile::where('user_id', $user->id)->firstOrFail();
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email',
'phone_number' => 'nullable|string|max:20',
'employee_id' => 'nullable|string|max:255',
'department_name' => 'nullable|string|max:255',
'programme_name' => 'nullable|string|max:255',
'salutation' => 'nullable|string|max:50',
'designation' => 'nullable|string|max:255',
'date_of_joining' => 'nullable|date',
'qualification' => 'nullable|string|max:500',
'address' => 'nullable|string|max:500',
'google_scholar_id' => 'nullable|string|max:255',
'vidhvan_id' => 'nullable|string|max:255',
'linkedin_id' => 'nullable|string|max:255',
'profile_photo' => 'nullable|image|max:2048', // 2MB max
]);
// Handle profile photo upload
if ($request->hasFile('profile_photo')) {
if ($profile->profile_photo_path && Storage::exists($profile->profile_photo_path)) {
Storage::delete($profile->profile_photo_path);
}
$validated['profile_photo_path'] = $request->file('profile_photo')
->store('public/profile_photos');
}
// Update profile with validated data
$profile->update([
'name' => $validated['name'] ?? $profile->name,
'email' => $validated['email'] ?? $profile->email,
'phone_number' => $validated['phone_number'] ?? '',
'employee_id' => $validated['employee_id'] ?? '',
'department_name' => $validated['department_name'] ?? '',
'programme_name' => $validated['programme_name'] ?? '',
'salutation' => $validated['salutation'] ?? '',
'designation' => $validated['designation'] ?? '',
'date_of_joining' => $validated['date_of_joining'] ?? $profile->date_of_joining,
'qualification' => $validated['qualification'] ?? '',
'address' => $validated['address'] ?? '',
'google_scholar_id' => $validated['google_scholar_id'] ?? '',
'vidhvan_id' => $validated['vidhvan_id'] ?? '',
'linkedin_id' => $validated['linkedin_id'] ?? '',
'profile_photo_path' => $validated['profile_photo_path'] ?? $profile->profile_photo_path,
]);
// ✅ Update the main user record (used by PublicationsController)
if ($request->filled('google_scholar_id')) {
$user->scholar_url = $request->input('google_scholar_id');
$user->save();
}
// ✅ Refresh session to ensure it reflects the latest Scholar URL immediately
Auth::setUser($user->fresh());
return redirect()
->route('faculty.profile.index')
->with('success', 'Profile updated successfully.');
}
}

View File

@@ -1,60 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;
class ProfileController extends Controller
{
/**
* Display the user's profile form.
*/
public function edit(Request $request): View
{
return view('profile.edit', [
'user' => $request->user(),
]);
}
/**
* Update the user's profile information.
*/
public function update(ProfileUpdateRequest $request): RedirectResponse
{
$request->user()->fill($request->validated());
if ($request->user()->isDirty('email')) {
$request->user()->email_verified_at = null;
}
$request->user()->save();
return Redirect::route('profile.edit')->with('status', 'profile-updated');
}
/**
* Delete the user's account.
*/
public function destroy(Request $request): RedirectResponse
{
$request->validateWithBag('userDeletion', [
'password' => ['required', 'current_password'],
]);
$user = $request->user();
Auth::logout();
$user->delete();
$request->session()->invalidate();
$request->session()->regenerateToken();
return Redirect::to('/');
}
}

View File

@@ -6,9 +6,19 @@ use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;
use App\Models\Publication;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Services\ScholarService;
class PublicationsController extends Controller
{
public function index()
{
$user = auth()->user();
$scholarUrl = $user->scholar_url;
return view('pages.publications.index', compact('scholarUrl'));
}
public function edit($id)
{
$publication = Publication::findOrFail($id);
@@ -23,7 +33,6 @@ class PublicationsController extends Controller
{
$publication = Publication::findOrFail($id);
// Validate the request data
$validated = $request->validate([
'first_author_name' => 'required|string',
'co_authors' => 'nullable|string',
@@ -43,34 +52,27 @@ class PublicationsController extends Controller
'paper_file' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,docx,zip',
]);
// Combine start date and time
$startDateTime = date('Y-m-d H:i:s', strtotime("{$validated['start_date']} {$validated['start_time']}"));
$endDateTime = date('Y-m-d H:i:s', strtotime("{$validated['end_date']} {$validated['end_time']}"));
// Handle the file upload if a new file is provided
if ($request->hasFile('paper_file')) {
// Delete old file if exists
if ($publication->paper_file && Storage::disk('public')->exists($publication->paper_file)) {
Storage::disk('public')->delete($publication->paper_file);
}
// Extract year from start_date
$year = date('Y', strtotime($validated['start_date']));
$username = $publication->user->name;
$originalName = $request->file('paper_file')->getClientOriginalName();
$fileName = $username . '_' . $originalName;
// Create path structure: year/faculty_name/Publications
$folderPath = 'proofs/' . $year . '/' . $username . '/Publications';
// Store file in the specified path
$paperFilePath = $request->file('paper_file')->storeAs($folderPath, $fileName, 'public');
$publication->paper_file = $paperFilePath;
}
// Update other fields
$publication->first_author_name = $validated['first_author_name'];
$publication->co_authors = $validated['co_authors'];
$publication->start_date = $startDateTime;
@@ -96,7 +98,6 @@ class PublicationsController extends Controller
return redirect()->route('coordinator.PublicationsResponses')
->with('status', 'Publication updated successfully');
} else {
// For regular users
return redirect()->route('faculty.PublicationsResponses')
->with('status', 'Publication updated successfully');
}
@@ -106,7 +107,6 @@ class PublicationsController extends Controller
{
$publication = Publication::findOrFail($id);
// Delete the file if it exists
if ($publication->paper_file && Storage::disk('public')->exists($publication->paper_file)) {
Storage::disk('public')->delete($publication->paper_file);
}
@@ -122,18 +122,14 @@ class PublicationsController extends Controller
$isAdmin = $user->role->name === 'Admin';
$isCoordinator = $user->role->name === 'Coordinator';
// Query based on role
if ($isAdmin) {
// Admin sees all records
$publications = Publication::with('user', 'department');
} elseif ($isCoordinator) {
// Coordinator sees only their department's records
$publications = Publication::with('user', 'department')
->whereHas('user', function ($query) use ($user) {
$query->where('department_id', $user->department_id);
});
} else {
// Regular users see only their own records
$publications = Publication::with('user', 'department')
->where('faculty_id', $user->id);
}
@@ -166,16 +162,13 @@ class PublicationsController extends Controller
->addColumn('action', function ($publication) {
$actions = [];
// View paper_file button for everyone
if ($publication->paper_file) {
$actions[] = '<a href="' . asset('storage/' . $publication->paper_file) . '" target="_blank" class="btn btn-sm btn-primary mr-1">View Paper</a>';
} else {
$actions[] = 'No Paper';
}
// Edit button with role-appropriate route
$userRole = auth()->user()->role->name;
// Determine the appropriate route based on user role
if ($userRole === 'Admin') {
$editRoute = route('admin.Publications.edit', $publication->id);
} elseif ($userRole === 'Coordinator') {
@@ -194,4 +187,135 @@ class PublicationsController extends Controller
->rawColumns(['action'])
->make(true);
}
}
/**
* Fetch all publications from user's linked Google Scholar profile.
*/
public function fetchScholar(Request $request)
{
try {
$user = auth()->user();
\Log::info('📡 FetchScholar Triggered', ['scholar_url' => $user->scholar_url]);
if (!$user || !$user->scholar_url) {
return response()->json([
'success' => false,
'message' => 'No Google Scholar URL found for the logged-in user.'
], 400);
}
$scholarService = new \App\Services\ScholarService();
$publications = $scholarService->fetchPublications($user->scholar_url);
if (empty($publications)) {
return response()->json([
'success' => false,
'message' => 'No publications found from the provided Scholar profile.'
]);
}
return response()->json([
'success' => true,
'count' => count($publications),
'data' => $publications,
]);
} catch (\Throwable $e) {
return response()->json([
'success' => false,
'message' => 'Error fetching publications: '.$e->getMessage(),
], 500);
}
}
/**
* Import selected publications (skipping duplicates).
*/
public function importScholar(Request $request)
{
try {
$user = auth()->user();
$facultyId = $user->id;
$validated = $request->validate([
'publications' => 'required|array',
'publications.*.title' => 'required|string',
'publications.*.authors' => 'nullable|string',
'publications.*.journal' => 'nullable|string',
'publications.*.year' => 'nullable|string',
'publications.*.link' => 'nullable|url',
]);
$rows = $validated['publications'];
$imported = 0;
$skipped = 0;
foreach ($rows as $pub) {
$exists = \App\Models\Publication::where('faculty_id', $facultyId)
->whereRaw('LOWER(title) = ?', [strtolower($pub['title'])])
->exists();
if ($exists) {
$skipped++;
continue;
}
// 🔹 Derive year safely (default to current year if blank)
$year = (int)($pub['year'] ?? date('Y'));
$year = ($year < 1900 || $year > date('Y') + 1) ? date('Y') : $year;
// 🔹 Set start/end to that year's first/last day
$startDate = "{$year}-01-01";
$endDate = "{$year}-12-31";
// 🔍 Smart Tag Detection
$journalLower = strtolower($pub['journal'] ?? '');
// Detect peer-reviewed journals
$isPeerReviewed = (
str_contains($journalLower, 'ieee') ||
str_contains($journalLower, 'elsevier') ||
str_contains($journalLower, 'springer') ||
str_contains($journalLower, 'scopus') ||
str_contains($journalLower, 'wiley') ||
str_contains($journalLower, 'nature') ||
str_contains($journalLower, 'taylor & francis')
) ? 'yes' : 'no';
// Detect Scopus / SCI tags
$isScopus = str_contains($journalLower, 'scopus') ? 'Yes' : 'No';
$isSci = str_contains($journalLower, 'sci') ? 'Yes' : 'No';
\App\Models\Publication::create([
'faculty_id' => $facultyId,
'department_id' => $user->department_id,
'affiliation' => $pub['journal'] ?? '-',
'organizing_institute' => null,
'venue_address' => null,
'title' => $pub['title'],
'first_author_name' => $user->name,
'co_authors' => $pub['authors'] ?? '-',
'journal_name' => $pub['journal'] ?? '-',
'start_date' => $startDate,
'end_date' => $endDate,
'num_days' => 365,
'activity_type' => 'Google Scholar',
'is_peer_reviewed' => $isPeerReviewed,
'is_scopus_indexed' => $isScopus,
'is_sci_indexed' => $isSci,
'external_link' => $pub['link'] ?? null,
]);
$imported++;
}
return response()->json([
'message' => "Imported $imported publications, skipped $skipped duplicates."
]);
} catch (\Throwable $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class FacultyProfile extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'name',
'email',
'phone_number',
'vidhvan_id',
'google_scholar_id',
'linkedin_id',
'designation',
'salutation',
'qualification',
'address',
'employee_id',
'department_name',
'programme_name',
'date_of_joining',
'profile_photo_path',
];
protected $casts = [
'qualification' => 'array',
'date_of_joining' => 'date',
];
// Each profile belongs to one user
public function user()
{
return $this->belongsTo(User::class);
}
}

View File

@@ -2,21 +2,14 @@
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',
@@ -27,24 +20,14 @@ class User extends Authenticatable
'scopus_id',
'mobile_no',
'extension',
'scholar_url', // ✅ added this line
];
/**
* 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 [
@@ -53,7 +36,6 @@ class User extends Authenticatable
];
}
public function role()
{
return $this->belongsTo(Role::class);

View File

@@ -0,0 +1,67 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class ScholarService
{
public function fetchPublications(string $url): array
{
try {
// Extract Google Scholar profile ID (e.g., ssU-uBEAAAAJ)
preg_match('/user=([^&]+)/', $url, $match);
$profileId = $match[1] ?? null;
if (!$profileId) {
\Log::warning('No Google Scholar ID found in URL: ' . $url);
return [];
}
// Load API key from .env
$apiKey = env('SERPAPI_KEY');
if (!$apiKey) {
\Log::error('SERPAPI_KEY not found in environment variables');
return [];
}
$endpoint = 'https://serpapi.com/search.json';
$response = Http::get($endpoint, [
'engine' => 'google_scholar_author',
'author_id' => $profileId,
'api_key' => $apiKey,
]);
if (!$response->successful()) {
\Log::error('Scholar API request failed: ' . $response->status());
return [];
}
$json = $response->json();
// Support multiple possible structures
$articles = $json['articles']
?? $json['publications']
?? $json['results']
?? [];
// ✅ Format and return
return collect($articles)
->map(function ($a) {
return [
'title' => $a['title'] ?? $a['name'] ?? null,
'authors' => $a['authors'] ?? ($a['author'] ?? null),
'journal' => $a['publication'] ?? $a['journal'] ?? null,
'year' => $a['year'] ?? ($a['publication_year'] ?? null),
'link' => $a['link'] ?? $a['citation_link'] ?? null,
];
})
->toArray();
} catch (\Throwable $e) {
\Log::error('ScholarService API error: ' . $e->getMessage());
return [];
}
}
}