Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

operation_module_code_clean #3751

Merged
merged 29 commits into from
Jan 9, 2025
Merged

Conversation

sagar1862000
Copy link
Contributor

@sagar1862000 sagar1862000 commented Dec 11, 2024

Refactor: Remove Operation Module, Clean up Dependencies, and Update Migrations

1. Complete Removal of the Operation Module:
Removed the entire operation module from the project, including related controllers, views, models, and other resources.
The operation module was no longer in use, and this cleanup helps streamline the project by removing unnecessary code and improving maintainability.

2. Removing Dependency of office_location from the CodeTrek Module:
Removed all references to the office_location table within the CodeTrek module, including any foreign key relations and logic that depended on this table.
The dependency on the centre_id in the code_trek_applicants table has been completely eliminated.
The migration file related to code_trek_applicants was updated to remove the centre_id column and clean up the database schema.

3. Removing Dependency of office_location from the Expenses Module:
Removed all references to the office_location table within the expenses module.
This includes both the removal of any foreign key constraints and logic that linked office_location to the expense-related data.
Adjustments were made in the models, controllers, and views to ensure that the module works independently of the office_location table.

4. Migration File Changes for code_trek_applicant:
A migration file was created to update the code_trek_applicants table, including the removal of the centre_id column.
The migration ensures the database schema reflects the removal of any dependencies on the office_location table.

5. Deletion of the office_location Table:
The office_location table was removed from the database as it was no longer required.

Summary by CodeRabbit

Release Notes

  • Major Changes

    • Removed Operations module and related office location functionality.
    • Eliminated centre/location selection features across multiple modules.
    • Simplified applicant and user management workflows.
  • Impact on User Experience

    • Removed ability to select or manage office locations.
    • Simplified navigation and form interfaces.
    • Reduced complexity in applicant and employee tracking.
  • Technical Cleanup

    • Removed deprecated routes, controllers, and associated database seeders.
    • Streamlined module structure and database schema.
  • Dependency Updates

    • Upgraded Google API Client from 2.4 to 2.10.
    • Added PHP CodeSniffer installer.
    • Adjusted PHP version compatibility.
  • Database Changes

    • Dropped office_locations table.
    • Removed centre_id references in applicant and user tables.

Copy link

coderabbitai bot commented Dec 11, 2024

Important

Review skipped

More than 25% of the files skipped due to max files limit. The review is being skipped to prevent a low-quality review.

68 files out of 150 files are above the max files limit of 75. Please upgrade to Pro plan to get higher limits.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request represents a comprehensive removal of the "Operations" module and associated office location functionality across multiple components of the application. The changes involve deleting entire modules, controllers, services, and views related to office locations, while also modifying existing code to remove references to centre or location-based features. The modifications span multiple modules, including CodeTrek, Expense, and User, indicating a significant architectural refactoring.

Changes

File/Module Change Summary
Modules/CodeTrek/* Removed centre/location references from applicant entities, controllers, and views
Modules/Expense/Resources/views/* Deleted location selection from expense creation and editing forms
Modules/Operations/ Entire module removed, including all controllers, services, routes, and configurations
app/Http/Controllers/HomeController.php Removed office location retrieval and user groups methods
config/constants.php Deleted office locations configuration
resources/views/* Removed location selection forms and navigation items
database/migrations/2024_12_11_173633_cleanup_office_location.php Added migration to clean up office location references in the database

Poem

🏢 Farewell, Office Locations! 🚪
Centres vanish like morning mist,
Modules deleted with a gentle twist,
No more dropdowns, no more space,
A clean slate with minimalist grace!
🌟 Code evolves, structures change 🌟

Finishing Touches

  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Outside diff range and nitpick comments (12)
composer.json (1)

OfficeSuite module files still present in the codebase

The verification reveals that the OfficeSuite module hasn't been completely removed:

  • Multiple PHP files still exist in the OfficeSuite directory with their respective namespaces
  • Active usage found in Modules/User/Services/UserService.php which depends on OfficeSuite\OfficeSuiteFacade
  • Complete module structure present including configs, contracts, services (GSuite, Office365), and provider
🔗 Analysis chain

Line range hint 82-86: Verify OfficeSuite namespace removal

The PR objectives mention removing the Operations module, but the OfficeSuite\\ namespace is still present in the autoload configuration. This might indicate incomplete removal of the module.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the OfficeSuite directory or any files within it still exist
if [ -d "OfficeSuite" ]; then
    echo "OfficeSuite directory still exists"
    find OfficeSuite -type f -name "*.php" | while read -r file; do
        echo "Found file: $file"
        head -n 1 "$file"  # Show the first line to verify namespace
    done
fi

# Search for any remaining references to OfficeSuite namespace
rg "namespace OfficeSuite" --type php
rg "use OfficeSuite" --type php

Length of output: 3718

resources/views/layouts/navbar.blade.php (3)

118-118: Remove unnecessary comment.

The comment "Deleted By Sagar" doesn't provide any value and should be removed. Git history already tracks who made the changes.

-  <!-- Deleted By Sagar -->

Line range hint 119-140: Fix duplicate HTML IDs in dropdown toggles.

Multiple dropdown toggles are using the same ID 'navbarDropdown_sales'. HTML IDs must be unique within the document.

Update the KnowledgeCafe dropdown ID:

-<a id="navbarDropdown_sales" class="nav-link dropdown-toggle"
+<a id="navbarDropdown_knowledge" class="nav-link dropdown-toggle"

Operations module removal needs additional cleanup

The Operations module has been removed from the navbar, but there are still several references to office locations in the codebase that need attention:

  • resources/views/hr/round-review-confirm-modal.blade.php: Contains a form field for office location
  • Modules/User/Entities/User.php: Has office location related attribute and meta data
  • Modules/HR/Http/Controllers/Recruitment/ApplicationController.php: Uses office location in email templates
  • Modules/HR/Database/Seeders/SettingsTableSeeder.php: Contains office location placeholder in email template
  • app/Http/Controllers/HomeController.php: Has commented out but lingering office location references

These references should either be removed or refactored to align with the Operations module removal.

🔗 Analysis chain

Line range hint 1-200: Verify complete removal of Operations module references.

The Operations section has been removed from the navbar as intended. Let's verify there are no remaining references to the Operations module or office locations in other view files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to Operations module or office locations in view files

echo "Checking for Operations module references..."
rg -i "operations" resources/views/ --type blade

echo "Checking for office location references..."
rg -i "office.?location|centre.?id" resources/views/ --type blade

Length of output: 370


Script:

#!/bin/bash
# Search for any remaining references to Operations module or office locations in view files
# Using plain text search without file type restriction

echo "Checking for Operations module references..."
rg -i "operations" resources/views/

echo "Checking for office location references..."
rg -i "office.?location|centre.?id" resources/views/

Length of output: 395


Script:

#!/bin/bash
# Let's check the context of the office location reference and verify if it's just a label or has functional dependencies

echo "Checking the round-review-confirm-modal.blade.php file content..."
cat resources/views/hr/round-review-confirm-modal.blade.php

echo -e "\nChecking for any office location related routes or controllers..."
rg -i "office.?location" --type php

Length of output: 8717

app/Http/Controllers/HomeController.php (1)

38-39: Define default location as a constant and improve error handling.

The default location should be defined as a constant, and we should add proper error handling for missing user meta.

Apply this diff:

+    private const DEFAULT_LOCATION = 'Default Location';
+
     public function index()
     {
         // ...
-        $selectedLocation = auth()->user()->office_location ?? 'Default Location';
+        try {
+            $selectedLocation = auth()->user()->office_location ?? self::DEFAULT_LOCATION;
+        } catch (\Exception $e) {
+            \Log::error('Failed to retrieve user location: ' . $e->getMessage());
+            $selectedLocation = self::DEFAULT_LOCATION;
+        }
Modules/CodeTrek/Http/Controllers/CodeTrekController.php (2)

Line range hint 19-19: Critical: Re-enable authorization checks

Multiple authorization checks are commented out throughout the controller with a note about "production issues". Disabling authorization checks exposes the application to potential security vulnerabilities by allowing unauthorized access to sensitive operations.

These checks should be re-enabled immediately after fixing the underlying production issues. Consider:

  1. Debugging the production issues with proper logging
  2. Implementing a temporary role-based fallback if needed
  3. Adding proper error handling around the authorization checks

Also applies to: 30-30, 54-54, 71-71, 82-82, 102-102


Line range hint 1-120: Enhance error handling and logging

The controller methods would benefit from proper error handling and logging, especially around database operations and service calls.

Consider wrapping critical operations in try-catch blocks and adding proper logging:

    public function store(Request $request)
    {
+       try {
            $data = $request->all();
            $this->service->store($data);
            return redirect()->route('codetrek.index');
+       } catch (\Exception $e) {
+           \Log::error('Failed to store CodeTrek applicant: ' . $e->getMessage());
+           return redirect()->back()->with('error', 'Failed to save applicant.');
+       }
    }
Modules/CodeTrek/Services/CodeTrekService.php (2)

Line range hint 83-88: Clean up commented code and improve implementation

The commented code and TODO-style comments should be handled more appropriately:

  1. Remove the commented centre_id assignment as it's no longer needed
  2. Move the mail queue implementation to a separate task/issue
-        // $applicant->centre_id = $data['centre'];
         $applicant->mentor_id = $data['mentorId'];
         $applicant->domain_name = $data['domain'];
         $applicant->latest_round_name = config('codetrek.rounds.introductory-call.slug');
-        // Mail::queue(new CodetrekMailApplicant($data)); This line will be uncommented in the future when the use of the codeTrek module starts in the proper way.
+        // TODO: Implement email notification in a separate PR
         $applicant->save();

Would you like me to create a GitHub issue to track the email notification implementation?


Line range hint 110-110: Remove remaining centre_id assignment

The update method still contains centre_id assignment which is inconsistent with the PR objectives of removing office_location dependencies.

-        $applicant->centre_id = $data['centre'] ?? null;
Modules/CodeTrek/Resources/views/edit.blade.php (2)

Line range hint 21-95: Consider extracting repeatable form groups into components

The form contains multiple similar form groups that could be extracted into reusable Blade components to improve maintainability and reduce duplication.

Consider creating components for:

  1. Text input groups
  2. Select input groups
  3. Form row wrapper

Example component structure:

// resources/views/components/form/text-input.blade.php
@props(['name', 'label', 'required' => false, 'type' => 'text'])
<div class="form-group col-md-5">
    <label for="{{ $name }}" @class(['field-required' => $required])>{{ $label }}</label>
    <input type="{{ $type }}" 
           class="form-control" 
           name="{{ $name }}" 
           id="{{ $name }}"
           {{ $attributes }}>
</div>

Usage:

<x-form.text-input
    name="first_name"
    label="First Name"
    required
    placeholder="Enter first name"
    :value="$applicant->first_name"
/>

Line range hint 67-80: Improve graduation year selection implementation

The graduation year calculation logic in the template could be moved to a dedicated helper or computed property.

Consider moving the logic to:

  1. A blade component with computed properties
  2. A view composer
  3. The controller

Example:

// In a view composer or controller
$graduationYears = collect(range(date('Y') + 4, 1990, -1))
    ->mapWithKeys(fn($year) => [$year => $year]);
Modules/Prospect/Resources/views/create.blade.php (1)

Line range hint 1-150: Consider implementing form validation using a dedicated form request class

The form contains multiple validation rules (required fields, URLs, etc.) implemented through HTML attributes. While HTML5 validation is good for client-side validation, it should be backed by server-side validation.

Consider:

  1. Creating a dedicated form request class for prospect creation
  2. Moving validation rules to the form request class
  3. Using Laravel's form validation features for consistent validation handling

Would you like me to help create a form request class with appropriate validation rules?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 15164b9 and fe16764.

📒 Files selected for processing (38)
  • Modules/CodeTrek/Entities/CodeTrekApplicant.php (1 hunks)
  • Modules/CodeTrek/Http/Controllers/CodeTrekController.php (3 hunks)
  • Modules/CodeTrek/Resources/views/edit.blade.php (1 hunks)
  • Modules/CodeTrek/Resources/views/index.blade.php (0 hunks)
  • Modules/CodeTrek/Resources/views/modals/add-applicant-modal.blade.php (0 hunks)
  • Modules/CodeTrek/Services/CodeTrekService.php (1 hunks)
  • Modules/Expense/Resources/views/create.blade.php (0 hunks)
  • Modules/Expense/Resources/views/edit.blade.php (0 hunks)
  • Modules/Operations/Config/config.php (0 hunks)
  • Modules/Operations/Database/Seeders/OfficeLocationTableSeeder.php (0 hunks)
  • Modules/Operations/Database/Seeders/OperationsDatabaseSeeder.php (0 hunks)
  • Modules/Operations/Database/Seeders/OperationsPermissionTableSeeder.php (0 hunks)
  • Modules/Operations/Entities/OfficeLocation.php (0 hunks)
  • Modules/Operations/Http/Controllers/OperationsController.php (0 hunks)
  • Modules/Operations/Providers/OperationsServiceProvider.php (0 hunks)
  • Modules/Operations/Providers/RouteServiceProvider.php (0 hunks)
  • Modules/Operations/Resources/views/layouts/master.blade.php (0 hunks)
  • Modules/Operations/Resources/views/modals/add-center-modal.blade.php (0 hunks)
  • Modules/Operations/Resources/views/office-location/edit.blade.php (0 hunks)
  • Modules/Operations/Resources/views/office-location/index.blade.php (0 hunks)
  • Modules/Operations/Routes/api.php (0 hunks)
  • Modules/Operations/Routes/web.php (0 hunks)
  • Modules/Operations/Services/OperationService.php (0 hunks)
  • Modules/Operations/composer.json (0 hunks)
  • Modules/Operations/module.json (0 hunks)
  • Modules/Operations/package.json (0 hunks)
  • Modules/Operations/policies/OperationsPolicy.php (0 hunks)
  • Modules/Operations/webpack.mix.js (0 hunks)
  • Modules/Prospect/Resources/views/create.blade.php (1 hunks)
  • app/Http/Controllers/HomeController.php (2 hunks)
  • composer.json (1 hunks)
  • config/constants.php (0 hunks)
  • database/migrations/2023_04_17_113950_create_office_locations_table.php (0 hunks)
  • database/migrations/2023_05_06_141606_add_centre_id_to_code_trek_applicant_table.php (2 hunks)
  • database/migrations/2024_12_11_173633_remove_centre_id_from_code_trek_applicants.php (1 hunks)
  • modules_statuses.json (0 hunks)
  • resources/views/home.blade.php (0 hunks)
  • resources/views/layouts/navbar.blade.php (1 hunks)
💤 Files with no reviewable changes (28)
  • Modules/Operations/module.json
  • Modules/Operations/Resources/views/office-location/edit.blade.php
  • Modules/Operations/composer.json
  • Modules/Operations/Entities/OfficeLocation.php
  • Modules/Operations/package.json
  • Modules/Operations/policies/OperationsPolicy.php
  • Modules/Operations/Config/config.php
  • Modules/Operations/webpack.mix.js
  • Modules/Operations/Database/Seeders/OperationsDatabaseSeeder.php
  • config/constants.php
  • Modules/Expense/Resources/views/create.blade.php
  • Modules/Operations/Resources/views/layouts/master.blade.php
  • Modules/Operations/Database/Seeders/OfficeLocationTableSeeder.php
  • modules_statuses.json
  • database/migrations/2023_04_17_113950_create_office_locations_table.php
  • Modules/Operations/Providers/RouteServiceProvider.php
  • Modules/Operations/Routes/api.php
  • Modules/Operations/Routes/web.php
  • resources/views/home.blade.php
  • Modules/Operations/Resources/views/modals/add-center-modal.blade.php
  • Modules/Operations/Database/Seeders/OperationsPermissionTableSeeder.php
  • Modules/CodeTrek/Resources/views/modals/add-applicant-modal.blade.php
  • Modules/Operations/Resources/views/office-location/index.blade.php
  • Modules/Expense/Resources/views/edit.blade.php
  • Modules/Operations/Http/Controllers/OperationsController.php
  • Modules/Operations/Providers/OperationsServiceProvider.php
  • Modules/CodeTrek/Resources/views/index.blade.php
  • Modules/Operations/Services/OperationService.php
✅ Files skipped from review due to trivial changes (1)
  • database/migrations/2023_05_06_141606_add_centre_id_to_code_trek_applicant_table.php
🔇 Additional comments (1)
Modules/Prospect/Resources/views/create.blade.php (1)

48-48: Verify the impact of POC user changes

Let's verify if this change aligns with the PR objectives and doesn't break any existing functionality.

✅ Verification successful

Let me gather more information about the POC user implementation to ensure there are no breaking changes.


Let me check the views to understand how the POC user selection is implemented and used.


POC user field implementation is properly integrated

The POC user field (poc_user_id) is correctly implemented across the codebase:

  • Required field validation in ProspectRequest
  • Foreign key constraint in the migration
  • Proper model relationship in Prospect model
  • Consistent usage in create/edit forms with proper validation
  • Proper handling in ProspectService for both create and update operations
  • Correct display in the prospect details view

The change in the create view is aligned with the existing implementation and maintains data integrity.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other files that might be affected by this POC user change
echo "Searching for related POC user references..."
rg -l "poc_user_id" --type php

# Check if there are any database migrations related to this field
echo "Checking for related migrations..."
fd -e php -p ".*create.*prospects.*" "database/migrations"

Length of output: 709


Script:

#!/bin/bash
# Check the migration file to understand the POC user field definition
echo "Checking migration file content..."
cat "Modules/Prospect/Database/Migrations/2024_10_19_235918_create-prospects-table.php"

# Check the model relationships and field definitions
echo -e "\nChecking Prospect model..."
cat "Modules/Prospect/Entities/Prospect.php"

# Check the validation rules
echo -e "\nChecking validation rules..."
cat "Modules/Prospect/Http/Requests/ProspectRequest.php"

Length of output: 4937


Script:

#!/bin/bash
# Check the views implementation
echo "Checking create view..."
cat "Modules/Prospect/Resources/views/create.blade.php"

echo -e "\nChecking prospect-details view..."
cat "Modules/Prospect/Resources/views/subviews/prospect-details.blade.php"

echo -e "\nChecking edit-prospect-details view..."
cat "Modules/Prospect/Resources/views/subviews/edit-prospect-details.blade.php"

# Check the service implementation
echo -e "\nChecking ProspectService..."
cat "Modules/Prospect/Services/ProspectService.php"

Length of output: 26609

composer.json Outdated
Comment on lines 62 to 63
"php": "7.5"
},
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix invalid PHP platform version

The platform configuration specifies PHP 7.5, which is not a valid PHP version (PHP versions went from 7.4 directly to 8.0). This conflicts with the requirement "php": "^7.4" and could cause dependency resolution issues.

   "platform": {
-    "php": "7.5"
+    "php": "7.4"
   },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"php": "7.5"
},
"php": "7.4"
},

Comment on lines +64 to 66
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add missing phpcodesniffer dependency

While the plugin is allowed, the dealerdirect/phpcodesniffer-composer-installer package is not listed in the dependencies. This could lead to the plugin not being available when needed.

Add the following to the require-dev section:

 "require-dev": {
+    "dealerdirect/phpcodesniffer-composer-installer": "^3.0",
     "barryvdh/laravel-debugbar": "^3.2",

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 16 to 19
Schema::table('code_trek_applicants', function (Blueprint $table) {
$table->dropForeign(['centre_id']); // Drops the foreign key constraint
$table->dropColumn('centre_id'); // Drops the column
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Code cleanup needed in CodeTrekService

The migration looks good, but there are still references to centre_id in Modules/CodeTrek/Services/CodeTrekService.php that need to be addressed:

  • Line 9: $applicants = $query->where('centre_id', $centre);
  • Line 10: $applicantCountData = $applicantCountData->where('centre_id', $centre)->get();
  • Line 12: $applicant->centre_id = $data['centre'] ?? null;

Additionally, there's a commented-out relationship in Modules/CodeTrek/Entities/CodeTrekApplicant.php that should be removed for code cleanliness.

🔗 Analysis chain

LGTM! Verify cascade effects.

The migration correctly handles the removal of both the foreign key constraint and the column. The order of operations is correct.

Let's verify there are no remaining references to centre_id:


Let me analyze the model relationships and validation rules to ensure we're not missing any dependencies before providing the final response.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to centre_id in the codebase
rg -i "centre_id|center_id" --type php

Length of output: 1839


Script:

#!/bin/bash
# Let's check if there are any models or controllers still using the relationship
ast-grep --pattern 'class CodeTrekApplicant extends Model {
  $$$
  public function $$$() {
    $$$belongsTo$$$centre$$$
  }
  $$$
}'

# Also check for any request validation rules using this field
ast-grep --pattern 'class $_ extends FormRequest {
  $$$
  public function rules() {
    return [
      $$$centre_id$$$
    ];
  }
  $$$
}'

Length of output: 277

Comment on lines 27 to 30
// public function center()
// {
// return $this->belongsTo(OfficeLocation::class, 'center_id');
// }
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove commented-out code instead of keeping it.

Since we're removing the office_location dependencies as per PR objectives, we should remove this commented-out code entirely rather than keeping it. Commented-out code creates technical debt and can confuse future developers.

Apply this diff:

-    // public function center()
-    // {
-    //     return $this->belongsTo(OfficeLocation::class, 'center_id');
-    // }

Comment on lines 32 to 36
$centres = collect([
['id' => 1, 'centre_name' => 'Center 1'],
['id' => 2, 'centre_name' => 'Center 2'],
['id' => 3, 'centre_name' => 'Center 3'],
])->sortBy('centre_name');
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Move hardcoded centers to configuration.

Hardcoding center data in the controller violates separation of concerns. This should be moved to a configuration file.

Create a new config file config/centers.php:

<?php
return [
    'centers' => [
        ['id' => 1, 'centre_name' => 'Center 1'],
        ['id' => 2, 'centre_name' => 'Center 2'],
        ['id' => 3, 'centre_name' => 'Center 3'],
    ]
];

Then update the controller:

-    $centres = collect([
-        ['id' => 1, 'centre_name' => 'Center 1'],
-        ['id' => 2, 'centre_name' => 'Center 2'],
-        ['id' => 3, 'centre_name' => 'Center 3'],
-    ])->sortBy('centre_name');
+    $centres = collect(config('centers.centers'))->sortBy('centre_name');

Comment on lines 84 to 86
// $request->validate([
// 'centre_name' => 'required|exists:office_locations,centre_name',
// ]);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove commented validation rules.

Since we're removing office_location dependencies, we should remove these commented-out validation rules entirely.

Apply this diff:

-        // $request->validate([
-        //     'centre_name' => 'required|exists:office_locations,centre_name',
-        // ]);
+        $request->validate([
+            'centre_name' => 'required|string',
+        ]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// $request->validate([
// 'centre_name' => 'required|exists:office_locations,centre_name',
// ]);
$request->validate([
'centre_name' => 'required|string',
]);

@@ -28,7 +27,7 @@ public function index(Request $request)
{
// $this->authorize('view', $applicant); There are some issues in the production, which is why these lines are commented out.

$centres = OfficeLocation::all();
// $centres = OfficeLocation::all();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove commented code instead of leaving it

The commented lines related to OfficeLocation should be removed rather than left as comments, as they're no longer needed according to the PR objectives.

-        // $centres = OfficeLocation::all();
-            // 'centres' => $centres,

Also applies to: 43-43

Comment on lines 48 to 56
<select name="poc_user_id" id="poc_user_id" class="form-control" required >
<option value="">Select POC User</option>
@foreach ($users as $user)
<option value="1">User</option>
<!-- @foreach ($users as $user)
<option value="{{ $user->id }}"
{{ old('poc_user_id') == $user->id ? 'selected' : '' }}>
{{ $user->name }}</option>
@endforeach
@endforeach -->
</select>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Hardcoded user selection needs attention

The POC user selection has been simplified to a single hardcoded user option, which seems incomplete and could limit functionality. Additionally, keeping commented-out code adds unnecessary noise to the codebase.

Consider these improvements:

  1. Restore dynamic user selection or provide justification for limiting to a single user
  2. Remove the commented-out code if it's no longer needed
-                                    <select name="poc_user_id" id="poc_user_id" class="form-control" required >
-                                        <option value="">Select POC User</option>
-                                        <option value="1">User</option>
-                                        <!-- @foreach ($users as $user)
-                                            <option value="{{ $user->id }}"
-                                                {{ old('poc_user_id') == $user->id ? 'selected' : '' }}>
-                                                {{ $user->name }}</option>
-                                        @endforeach -->
+                                    <select name="poc_user_id" id="poc_user_id" class="form-control" required>
+                                        <option value="">Select POC User</option>
+                                        @foreach ($users as $user)
+                                            <option value="{{ $user->id }}"
+                                                {{ old('poc_user_id') == $user->id ? 'selected' : '' }}>
+                                                {{ $user->name }}</option>
+                                        @endforeach
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<select name="poc_user_id" id="poc_user_id" class="form-control" required >
<option value="">Select POC User</option>
@foreach ($users as $user)
<option value="1">User</option>
<!-- @foreach ($users as $user)
<option value="{{ $user->id }}"
{{ old('poc_user_id') == $user->id ? 'selected' : '' }}>
{{ $user->name }}</option>
@endforeach
@endforeach -->
</select>
<select name="poc_user_id" id="poc_user_id" class="form-control" required>
<option value="">Select POC User</option>
@foreach ($users as $user)
<option value="{{ $user->id }}"
{{ old('poc_user_id') == $user->id ? 'selected' : '' }}>
{{ $user->name }}</option>
@endforeach

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
app/Http/Controllers/HomeController.php (1)

Office location functionality requires comprehensive removal

The codebase shows multiple components still depending on the office location feature that need to be addressed:

  • Route: /current-employee-location in routes/web.php
  • Models: User model has office_location accessor in Modules/User/Entities/User.php
  • Views: Location references in resources/views/hr/round-review-confirm-modal.blade.php
  • Database: Foreign key references to office_locations table in migrations
  • Controller: Location-related code in HomeController.php

For a clean removal, all these components should be removed or updated accordingly to maintain codebase consistency.

🔗 Analysis chain

Line range hint 1-85: Verify complete removal of location functionality

To ensure complete removal of office_location dependencies, we need to verify related components.


Office location functionality needs complete cleanup

Several components still reference the office location functionality that appears to be in the process of removal:

  • Route definition in routes/web.php for employee location updates
  • Foreign key references to office_locations table in migrations
  • User model in Modules/User/Entities/User.php has office_location accessor
  • Location-related code in HomeController.php
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining references to office_location and related functionality

# Check routes referencing storeEmployeeLocation
echo "Checking routes..."
rg "storeEmployeeLocation" routes/

# Check views using selectedLocation
echo "Checking views..."
rg "selectedLocation" resources/views/

# Check remaining office_location references
echo "Checking office_location references..."
rg "office_location"

# Check UserMeta usage for office_location
echo "Checking UserMeta office_location usage..."
rg -A 3 "meta_key.*office_location"

Length of output: 1817


Script:

#!/bin/bash
# Let's verify if there are any views or templates using this functionality
# and check for the office_locations table structure

# Check for any view files referencing location
echo "Checking views for location references..."
rg -i "location|centre" resources/views/

# Check for office_locations table references
echo "Checking office_locations table references..."
fd -e php | xargs rg "office_locations"

# Check for any location-related forms
echo "Checking for location forms..."
rg -i "form.*location|location.*form" resources/views/

Length of output: 3032

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7b9b2ee and ca3f5fe.

📒 Files selected for processing (4)
  • Modules/CodeTrek/Entities/CodeTrekApplicant.php (0 hunks)
  • Modules/CodeTrek/Http/Controllers/CodeTrekController.php (1 hunks)
  • Modules/CodeTrek/Resources/views/index.blade.php (0 hunks)
  • app/Http/Controllers/HomeController.php (3 hunks)
💤 Files with no reviewable changes (2)
  • Modules/CodeTrek/Entities/CodeTrekApplicant.php
  • Modules/CodeTrek/Resources/views/index.blade.php
🚧 Files skipped from review as they are similar to previous changes (1)
  • Modules/CodeTrek/Http/Controllers/CodeTrekController.php

Comment on lines 32 to 35
return view('home')->with([
'book' => $unreadBook,
'selectedLocation' => $selectedLocation,
]);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider removing location-related view data

Since we're removing the office_location functionality as per PR objectives, we should also remove the selectedLocation from the view data.

Apply this diff:

return view('home')->with([
    'book' => $unreadBook,
-    'selectedLocation' => $selectedLocation,
]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return view('home')->with([
'book' => $unreadBook,
'selectedLocation' => $selectedLocation,
]);
return view('home')->with([
'book' => $unreadBook,
]);

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
Modules/CodeTrek/Resources/views/index.blade.php (2)

Line range hint 90-95: Clean up remaining centre references in navigation

There are still references to the centre parameter in various parts of the template:

  • URL parameter generation for navigation
  • Hidden inputs in forms

Remove all remaining centre references from the navigation and filtering logic:

-$centre = request()->get('centre');
// ... and remove 'centre' from all route parameters, e.g.:
-    <input type="hidden" name="centre" value="{{ request()->get('centre') }}">

Also applies to: 150-155


257-303: Enhance Vue.js component robustness

While the changes improve the code, consider these enhancements:

  1. Add frontend validation before submission
  2. Implement proper loading state management
  3. Add type checking for response data

Consider this enhancement:

 methods: {
+    validateForm(formData) {
+        const required = ['first_name', 'email'];
+        for (const field of required) {
+            if (!formData.get(field)) {
+                this.$toast.error(`${field} is required`);
+                return false;
+            }
+        }
+        return true;
+    },
     submitForm: async function(formId) {
         $('.save-btn').attr('disabled', true);
+        this.isLoading = true;
         let formData = new FormData(document.getElementById(formId));
+        
+        if (!this.validateForm(formData)) {
+            $('.save-btn').attr('disabled', false);
+            this.isLoading = false;
+            return;
+        }
         
         await axios.post(storeUrl, formData)
             .then((response) => {
+                if (!response?.data?.success) {
+                    throw new Error('Invalid response format');
+                }
                 // ... rest of success handling
             })
             .catch((error) => {
+                const errorMessage = error.response?.data?.errors 
+                    ? Object.values(error.response.data.errors)[0][0]
+                    : 'An unexpected error occurred';
+                this.$toast.error(errorMessage);
             })
+            .finally(() => {
+                this.isLoading = false;
+            });
     }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ca3f5fe and b98ade0.

⛔ Files ignored due to path filters (1)
  • composer.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • Modules/CodeTrek/Resources/views/index.blade.php (1 hunks)
  • Modules/CodeTrek/Services/CodeTrekService.php (0 hunks)
  • app/Http/Controllers/HomeController.php (2 hunks)
  • app/Models/KnowledgeCafe/WeeklyDose.php (1 hunks)
  • composer.json (2 hunks)
  • database/migrations/2024_12_11_173633_remove_centre_id_from_code_trek_applicants.php (1 hunks)
💤 Files with no reviewable changes (1)
  • Modules/CodeTrek/Services/CodeTrekService.php
✅ Files skipped from review due to trivial changes (1)
  • app/Models/KnowledgeCafe/WeeklyDose.php
🚧 Files skipped from review as they are similar to previous changes (2)
  • database/migrations/2024_12_11_173633_remove_centre_id_from_code_trek_applicants.php
  • composer.json
🔇 Additional comments (2)
app/Http/Controllers/HomeController.php (2)

30-35: ⚠️ Potential issue

Remove remaining office_location dependencies

The PR objectives specify removing all office_location dependencies, but this code still relies on them. The office_location attribute and view data should be removed entirely.

Apply this diff:

-    $selectedLocation = auth()->user()->office_location ?? 'Default Location';
-
     return view('home')->with([
-        'book' => $unreadBook,
-        'selectedLocation' => $selectedLocation,
+        'book' => $unreadBook
     ]);

Likely invalid or redundant comment.


Line range hint 75-86: Remove storeEmployeeLocation method

This entire method should be removed as it maintains office_location functionality, which contradicts the PR objectives of removing all office_location dependencies.

Remove the entire storeEmployeeLocation method as it's no longer needed.

Additionally, verify if there are any routes or views still referencing this method:

Comment on lines 48 to 72
// public function getUserGroups($email)
// {
// $client = new Google_Client();
// $client->useApplicationDefaultCredentials();
// $client->setSubject(env('GOOGLE_SERVICE_ACCOUNT_IMPERSONATE'));
// $client->addScope([
// Google_Service_Directory::ADMIN_DIRECTORY_GROUP,
// Google_Service_Directory::ADMIN_DIRECTORY_GROUP_READONLY,
// ]);

$userGroups = [];
if (count($groups)) {
foreach ($groups as $group) {
$userGroups[$group->email] = $group->name;
}
}
// $dir = new Google_Service_Directory($client);
// $googleGroups = $dir->groups->listGroups([
// 'userKey' => $email,
// ]);
// $groups = $googleGroups->getGroups();

return $userGroups;
}
// $userGroups = [];
// if (count($groups)) {
// foreach ($groups as $group) {
// $userGroups[$group->email] = $group->name;
// }
// }

// return $userGroups;
// }
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove commented code

Commented-out code should be removed as it adds unnecessary noise to the codebase. If this functionality is needed in the future, it can be retrieved from version control history.

Remove the entire commented getUserGroups method.

Copy link

cypress bot commented Dec 12, 2024

Employee portal    Run #8947

Run Properties:  status check passed Passed #8947  •  git commit 03c944e52a ℹ️: Merge db46c19527b729c9d479f3feb986c435358047e4 into 73a3aedab79aa4e8502e43cd9a24...
Project Employee portal
Branch Review refs/pull/3751/merge
Run status status check passed Passed #8947
Run duration 00m 25s
Commit git commit 03c944e52a ℹ️: Merge db46c19527b729c9d479f3feb986c435358047e4 into 73a3aedab79aa4e8502e43cd9a24...
Committer Sagar Sharma
View all properties for this run ↗︎

Test results
Tests that failed  Failures 0
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 4
View all changes introduced in this branch ↗︎

Copy link
Contributor

github-actions bot commented Dec 12, 2024

Coverage report for commit: db46c19
File: coverage.xml

Cover ┌─────────────────────────┐ Freq.
   0% │ ███████████████████████ │ 76.2%
  10% │ █░░░░░░░░░░░░░░░░░░░░░░ │  0.6%
  20% │ █░░░░░░░░░░░░░░░░░░░░░░ │  0.6%
  30% │ █░░░░░░░░░░░░░░░░░░░░░░ │  0.3%
  40% │ █░░░░░░░░░░░░░░░░░░░░░░ │  0.3%
  50% │ ██░░░░░░░░░░░░░░░░░░░░░ │  4.0%
  60% │ █░░░░░░░░░░░░░░░░░░░░░░ │  1.2%
  70% │ █░░░░░░░░░░░░░░░░░░░░░░ │  0.3%
  80% │ █░░░░░░░░░░░░░░░░░░░░░░ │  0.9%
  90% │ █░░░░░░░░░░░░░░░░░░░░░░ │  3.1%
 100% │ ████░░░░░░░░░░░░░░░░░░░ │ 12.3%
      └─────────────────────────┘
 *Legend:* █ = Current Distribution 
Summary - Lines: 7.17% | Methods: 8.99%
FilesLinesMethodsBranches
Modules/HR/Console
   JobExpiredEmailToHr.php--100.00%
   QuarterlyReviewSystemForEmployee.php--100.00%
Modules/HR/Console/Recruitment
   ApplicationNoShow.php--100.00%
   DailyMessage.php--100.00%
   MappingOfJobsAndHrRounds.php--100.00%
   MarkApplicationForFollowUp.php--100.00%
   MoveFilesToWordPress.php--100.00%
   ResetIsLatestApplicationRound.php45.45%66.67%100.00%
   SendFollowUpThresholdMail.php--100.00%
   SendInterviewReminders.php--100.00%
Modules/HR/Contracts
   ApplicationServiceContract.php100.00%100.00%100.00%
   EvaluationServiceContract.php100.00%100.00%100.00%
   UniversityServiceContract.php100.00%100.00%100.00%
Modules/HR/Database/Factories
   HrApplicantsFactory.php100.00%100.00%100.00%
   HrApplicationEvaluationFactory.php--100.00%
   HrApplicationMetaFactory.php--100.00%
   HrApplicationRejectionFactory.php--100.00%
   HrApplicationRoundReviewFactory.php--100.00%
   HrApplicationSegmentFactory.php--100.00%
   HrApplicationsFactory.php--100.00%
   HrEmployeeFactory.php--100.00%
   HrFollowUpFactory.php--100.00%
   HrJobsFactory.php--100.00%
   HrResourcesCategoriesFactory.php--100.00%
   HrResourcesFactory.php--100.00%
   HrUniversitiesContactsFactory.php100.00%100.00%100.00%
   HrUniversitiesFactory.php100.00%100.00%100.00%
   HrUniversityAliasesFactory.php100.00%100.00%100.00%
Modules/HR/Database/Migrations
   2020_07_15_110611_create_hr_application_segments_table.php91.67%50.00%100.00%
   2020_07_15_142215_rename_next_interview_comments_column.php50.00%50.00%100.00%
   2020_07_25_202622_update_segment_table_with_segment_parent.php61.54%50.00%100.00%
   2020_09_04_234639_update_application_round_with_calendar_meeting_id.php66.67%50.00%100.00%
   2020_09_06_234443_update_hr_application_round_table_with_is_latest.php50.00%50.00%100.00%
   2020_09_07_171154_create_hr_follow_ups_table.php92.31%50.00%100.00%
   2020_09_08_073438_create_hr_universities_table.php87.50%50.00%100.00%
   2020_09_08_073538_create_hr_universities_contacts_table.php90.00%50.00%100.00%
   2020_09_08_073651_add_hr_university_id_to_hr_applicants_table.php42.86%50.00%100.00%
   2020_11_24_141131_create_hr_university_aliases_table.php85.71%50.00%100.00%
   2020_12_31_112259_alter_posted_by_in_hr_jobs_table.php50.00%50.00%100.00%
   2021_01_01_113149_add_status_to_hr_jobs_table.php50.00%50.00%100.00%
   2021_01_01_123714_add_soft_deletes_to_hr_jobs_table.php50.00%50.00%100.00%
   2022_03_08_064931_update_hr_jobs_table.php50.00%50.00%100.00%
   2022_06_15_141424_add_parameter_slug_column_in_evaluation_parameter_table.php50.00%50.00%100.00%
   2022_07_04_165601_add_verification_status_to_application.php50.00%50.00%100.00%
   2022_07_07_075310_create_hr_job_domains_table.php85.71%50.00%100.00%
   2022_07_15_115016_create_hr_channels_table.php85.71%50.00%100.00%
   2022_07_15_115134_update_hr_applications_with_hr_channels_table.php50.00%50.00%100.00%
   2022_09_01_230847_create_job_requisition_table.php57.14%50.00%100.00%
   2022_09_06_232653_add_status_to_job_requisition.php50.00%50.00%100.00%
   2022_09_12_140344_create_hr_applicant_meta_table.php76.92%50.00%100.00%
   2022_09_19_160414_create_hr_job_designation_table.php85.71%50.00%100.00%
   2022_09_21_145858_create_batch_members_table.php57.14%50.00%100.00%
   2022_09_21_151304_create_batches_table.php83.33%50.00%100.00%
   2022_09_26_134702_alter_column_for_application_meta_value.php50.00%50.00%100.00%
   2024_03_20_161855_add_commencement_date_column_to_employee_salary_table.php50.00%50.00%100.00%
Modules/HR/Database/Seeders
   AddPreparatoryRoundsSeeder.php--100.00%
   ApplicationEvaluationTableSeeder.php--100.00%
   DomainTableSeeder.php--100.00%
   HRDatabaseSeeder.php--100.00%
   HRJobsSeederTableSeeder.php--100.00%
   HRPermissionsTableSeeder.php--100.00%
   HRRoundsTableSeeder.php--100.00%
   HrApplicantsTableSeeder.php--100.00%
   HrApplicationEvaluationSegmentTableSeeder.php--100.00%
   HrApplicationMetaTableSeeder.php--100.00%
   HrApplicationRejectionReasonTableSeeder.php--100.00%
   HrApplicationRoundReviewTableSeeder.php--100.00%
   HrApplicationRoundTableSeeder.php--100.00%
   HrApplicationSegmentTableSeeder.php--100.00%
   HrApplicationsTableSeeder.php--100.00%
   HrChannelsTableSeeder.php--100.00%
   HrDesignationTableSeeder.php100.00%100.00%100.00%
   HrDomainTableSeeder.php100.00%100.00%100.00%
   HrFollowUpTableSeeder.php--100.00%
   HrResourcesCategoriesTableSeeder.php--100.00%
   HrResourcesTableSeeder.php--100.00%
   HrUniversitiesContactsTableSeeder.php--100.00%
   HrUniversitiesTableSeeder.php--100.00%
   HrUniversityAliasesTableSeeder.php--100.00%
   ResumeScreeningEvaluationSeeder.php--100.00%
   SettingsTableSeeder.php--100.00%
   TagTableSeeder.php--100.00%
Modules/HR/Emails
   AppointmentSlotSelectionMail.php--100.00%
   SendHiringMail.php--100.00%
   SendJobExpiredMail.php--100.00%
   SendPayrollListMail.php--100.00%
   SendThreshholdFollowUp.php--100.00%
Modules/HR/Emails/Recruitment/Applicant
   ApplicantCreateAutoResponder.php--100.00%
   NoShow.php--100.00%
   OnHold.php--100.00%
   RoundReviewed.php--100.00%
   ScheduledInterviewReminder.php--100.00%
Modules/HR/Emails/Recruitment/Application
   ApplicationHandover.php--100.00%
   CustomApplicationMail.php--100.00%
   JobChanged.php--100.00%
   RoundNotConducted.php--100.00%
Modules/HR/Emails/Recruitment
   InterviewerScheduledRoundsReminder.php--100.00%
   SendForApproval.php--100.00%
   SendOfferLetter.php--100.00%
Modules/HR/Entities
   Applicant.php1.69%10.00%100.00%
   ApplicantMeta.php--100.00%
   Application.php--100.00%
   ApplicationEvaluationSegment.php--100.00%
   ApplicationMeta.php--100.00%
   ApplicationRound.php--100.00%
   ApplicationRoundReview.php--100.00%
   Assessment.php--100.00%
   Employee.php1.47%4.55%100.00%
   FollowUp.php--100.00%
   HRJobsRounds.php100.00%100.00%100.00%
   HRRejectionReason.php--100.00%
   HRRequisitionHiredBatch.php--100.00%
   HRRequisitionHiredBatchMembers.php--100.00%
   HrChannel.php100.00%100.00%100.00%
   HrJobDesignation.php--100.00%
   HrJobDomain.php--100.00%
   IndividualAssessment.php--100.00%
   Job.php--100.00%
   JobRequisition.php--100.00%
   Round.php--100.00%
   University.php33.33%33.33%100.00%
   UniversityAlias.php100.00%100.00%100.00%
   UniversityContact.php100.00%100.00%100.00%
Modules/HR/Entities/Evaluation
   ApplicationEvaluation.php--100.00%
   Parameter.php--100.00%
   ParameterOption.php--100.00%
   Segment.php--100.00%
Modules/HR/Events
   ApplicationMovedToNewRound.php--100.00%
   CustomMailTriggeredForApplication.php--100.00%
   FollowUpEvent.php--100.00%
   InterviewCommunicationEmailSent.php--100.00%
Modules/HR/Events/Recruitment
   ApplicantEmailVerified.php--100.00%
   ApplicationCreated.php--100.00%
   JobUpdated.php--100.00%
Modules/HR/Exports
   ContractorFeeExport.php--100.00%
   EmployeePayrollExport.php--100.00%
Modules/HR/Helpers
   TemplateHelper.php--100.00%
Modules/HR/Http/Controllers
   EmployeeController.php--100.00%
   EvaluationController.php--100.00%
   HiringController.php--100.00%
   HrChannelController.php--100.00%
   HrJobDesignationController.php--100.00%
   RequisitionController.php--100.00%
   ResourcesController.php--100.00%
   TagsController.php--100.00%
Modules/HR/Http/Controllers/Recruitment
   ApplicantController.php--100.00%
   ApplicationController.php--100.00%
   ApplicationRoundController.php--100.00%
   CampaignsController.php--100.00%
   InternshipApplicationController.php--100.00%
   JobApplicationController.php--100.00%
   JobController.php--100.00%
Table truncated to fit comment

🤖 comment via lucassabreu/comment-coverage-clover

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
app/Http/Controllers/HomeController.php (1)

Line range hint 1-58: Ensure complete removal of office location functionality

The current implementation appears to be an incomplete removal of the office location functionality. For a clean architectural separation:

  1. Remove all office location references from the User model
  2. Remove the office_location meta_key handling from UserMeta
  3. Update all views to remove location-related UI elements
  4. Remove related routes from the router configuration

This ensures we don't leave behind partially implemented features.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 99da9e1 and 933e3d0.

📒 Files selected for processing (2)
  • app/Http/Controllers/HomeController.php (2 hunks)
  • database/migrations/2023_05_06_141606_add_centre_id_to_code_trek_applicant_table.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • database/migrations/2023_05_06_141606_add_centre_id_to_code_trek_applicant_table.php
🔇 Additional comments (1)
app/Http/Controllers/HomeController.php (1)

5-8: LGTM: Import changes are appropriate

The added imports for Book model and RedirectResponse are correctly aligned with their usage in the code.

Comment on lines 27 to 34

$unreadBook = session('disable_book_suggestion') ? null : Book::getRandomUnreadBook();
$centres = OfficeLocation::orderBy('centre_name', 'asc')->get();

$selectedLocation = auth()->user()->office_location;
$selectedLocation = auth()->user()->office_location ?? 'Default Location';

return view('home')->with([
'book' => $unreadBook,
'centres' => $centres,
'selectedLocation' => $selectedLocation,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove remaining office_location dependencies

This code segment still contains office location references despite the PR objective to remove all office_location dependencies.

Apply this diff to align with PR objectives:

-        $selectedLocation = auth()->user()->office_location ?? 'Default Location';
-
         return view('home')->with([
-            'book' => $unreadBook,
-            'selectedLocation' => $selectedLocation,
+            'book' => $unreadBook
         ]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$unreadBook = session('disable_book_suggestion') ? null : Book::getRandomUnreadBook();
$centres = OfficeLocation::orderBy('centre_name', 'asc')->get();
$selectedLocation = auth()->user()->office_location;
$selectedLocation = auth()->user()->office_location ?? 'Default Location';
return view('home')->with([
'book' => $unreadBook,
'centres' => $centres,
'selectedLocation' => $selectedLocation,
$unreadBook = session('disable_book_suggestion') ? null : Book::getRandomUnreadBook();
return view('home')->with([
'book' => $unreadBook
]);

Comment on lines 39 to 56
* Store the user's office location.
*
* @return array List of groups
* @param Request $request
* @return RedirectResponse
*/
public function getUserGroups($email)
public function storeEmployeeLocation(Request $request): RedirectResponse
{
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject(env('GOOGLE_SERVICE_ACCOUNT_IMPERSONATE'));
$client->addScope([
Google_Service_Directory::ADMIN_DIRECTORY_GROUP,
Google_Service_Directory::ADMIN_DIRECTORY_GROUP_READONLY,
]);

$dir = new Google_Service_Directory($client);
$googleGroups = $dir->groups->listGroups([
'userKey' => $email,
]);
$groups = $googleGroups->getGroups();

$userGroups = [];
if (count($groups)) {
foreach ($groups as $group) {
$userGroups[$group->email] = $group->name;
}
}

return $userGroups;
}

public function storeEmployeeLocation(Request $request)
{
$request->validate([
'centre_name' => 'required|exists:office_locations,centre_name',
'centre_name' => 'required|string|max:255',
]);

UserMeta::updateOrCreate(
['user_id' => auth()->user()->id, 'meta_key' => 'office_location'],
['meta_value' => $request->centre_name]
);

return redirect('home');
return redirect()->route('home')->with('status', 'Location updated successfully!');
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

Remove storeEmployeeLocation method and its route

The verification confirms this functionality should be removed:

  • Route defined in routes/web.php: Route::post('/current-employee-location', 'HomeController@storeEmployeeLocation')
  • Method in HomeController.php storing location in UserMeta table
  • No active references in views/JS files to this route
  • The only centre_name reference in views is unrelated (CodeTrek module's centre selection)

Required changes:

  • Delete the storeEmployeeLocation method from HomeController.php
  • Remove the route definition Route::post('/current-employee-location'...) from routes/web.php
🔗 Analysis chain

Remove storeEmployeeLocation method

This entire method should be removed as it contradicts the PR objective of removing office location functionality. The method still handles storing office locations in UserMeta, which should be eliminated as part of this refactoring.

Let's verify if this method is still referenced:

After confirming no active references, remove the entire method and its corresponding route definition.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for route definitions or view references to storeEmployeeLocation
rg -l "storeEmployeeLocation|route\(['\"]store.employee.location" 

Length of output: 124


Script:

#!/bin/bash
# Let's check the route definition and any related view files
rg "storeEmployeeLocation|route\(['\"]store.employee.location" -A 2 -B 2

Length of output: 730


Script:

#!/bin/bash
# Let's check if there are any views or JavaScript files referencing this route
rg -i "update\.employee\.location|current-employee-location" --type html --type js -A 2 -B 2

# Also check for any references to the centre_name field
rg "centre_name" -A 2 -B 2

Length of output: 1401

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
app/Http/Controllers/HomeController.php (1)

Line range hint 1-84: Architectural Cleanup Required

The current state of this controller still maintains office location functionality, which contradicts the PR's primary objective of removing the operation module and office_location dependencies. To maintain architectural consistency:

  1. Remove all office location related code from this controller
  2. Update related views to remove location references
  3. Consider updating tests that might be expecting location data

Would you like assistance in generating a comprehensive cleanup plan?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 933e3d0 and e39eb25.

📒 Files selected for processing (1)
  • app/Http/Controllers/HomeController.php (1 hunks)
🔇 Additional comments (3)
app/Http/Controllers/HomeController.php (3)

30-35: ⚠️ Potential issue

Remove remaining office_location dependencies

This code segment still contains office location references despite the PR objective to remove all office_location dependencies.

Apply this diff to align with PR objectives:

-        $selectedLocation = auth()->user()->office_location ?? 'Default Location';
-
         return view('home')->with([
-            'book' => $unreadBook,
-            'selectedLocation' => $selectedLocation,
+            'book' => $unreadBook
         ]);

38-70: 🛠️ Refactor suggestion

Remove commented code

Commented-out code should be removed as it adds unnecessary noise to the codebase. If this functionality is needed in the future, it can be retrieved from version control history.

Remove the entire commented getUserGroups method.


Line range hint 72-84: Remove storeEmployeeLocation method and its route

This method should be removed entirely as it contradicts the PR objective of removing office location functionality. The method still handles storing office locations in UserMeta.

Let's verify if this method is still referenced:

Required changes:

  1. Delete the storeEmployeeLocation method from HomeController.php
  2. Remove the route definition from routes/web.php
  3. Remove any view/JS references to this endpoint

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
database/migrations/2024_12_11_173633_cleanup_office_location.php (1)

30-35: Use unsignedBigInteger for consistency.
When referencing a typical users.id column, it’s best practice to use $table->unsignedBigInteger('centre_head_id'); to avoid potential conflicts and maintain consistency with Laravel’s default bigIncrements for the id column in the users table.

- $table->integer('centre_head_id')->unsigned();
+ $table->unsignedBigInteger('centre_head_id');
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d983b40 and d8ad8aa.

📒 Files selected for processing (4)
  • Modules/CodeTrek/Resources/views/index.blade.php (7 hunks)
  • app/Http/Controllers/HomeController.php (0 hunks)
  • database/migrations/2024_12_11_173633_cleanup_office_location.php (1 hunks)
  • resources/views/layouts/navbar.blade.php (0 hunks)
💤 Files with no reviewable changes (2)
  • resources/views/layouts/navbar.blade.php
  • app/Http/Controllers/HomeController.php
🚧 Files skipped from review as they are similar to previous changes (1)
  • Modules/CodeTrek/Resources/views/index.blade.php
🔇 Additional comments (1)
database/migrations/2024_12_11_173633_cleanup_office_location.php (1)

42-43: Align foreign key column types.
centre_id in code_trek_applicants is created as unsignedBigInteger, which is good. Ensure that all references here and in other relevant tables consistently use the same type, preventing range mismatch and foreign key conflicts.

Comment on lines 17 to 18
$table->dropForeign('centre_id');
$table->dropColumn('centre_id');
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Foreign key constraint name needs to be corrected

The foreign key constraint name should be code_trek_applicants_centre_id_foreign based on Laravel's naming convention. The current migration and the original migration that created this foreign key both use an incorrect constraint name 'centre_id'. This should be updated to:

$table->dropForeign(['centre_id']);  // Use array syntax with column name
  • Location: database/migrations/2024_12_11_173633_cleanup_office_location.php:17

The current code could fail during migration because Laravel automatically names foreign key constraints as {table_name}_{column_name}_foreign. This pattern is evident from the Laravel documentation and is a standard convention. Both the original migration that added this constraint and this cleanup migration are using an incorrect constraint name, which needs to be fixed to ensure successful migration execution.

🔗 Analysis chain

Potential mismatch in foreign key name.
Laravel typically names constraints in the format table_column_foreign. If your actual foreign key constraint name differs from 'centre_id', this migration could fail. Please confirm or use $table->dropForeign(['centre_id']) to ensure consistency.

Run the following script to search for how Laravel named the foreign key:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check existing migration logic for foreign key naming
rg -A 2 $'foreignId\\(\\\'centre_id\\\'\\)' 

Length of output: 148


Script:

#!/bin/bash
# Let's search for foreign key definitions in migrations
rg -l "foreign|foreignId" database/migrations/

Length of output: 4194


Script:

#!/bin/bash
# Let's look at the content of the migration file
cat database/migrations/2024_12_11_173633_cleanup_office_location.php

Length of output: 1446


Script:

#!/bin/bash
# Let's search for any previous migrations that might have created this foreign key
rg -l "centre_id" database/migrations/

Length of output: 189


Script:

#!/bin/bash
# Let's examine the table structure in schema
rg "Schema::create.*office_location" -A 10 database/migrations/

Length of output: 2592


Script:

#!/bin/bash
# Let's check the migration that added the centre_id column to see how the foreign key was named
cat database/migrations/2023_05_06_141606_add_centre_id_to_code_trek_applicant_table.php

Length of output: 926

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
.php-cs-fixer.php (1)

85-88: LGTM! The new PHPDoc rules enhance documentation consistency.

The addition of phpdoc_no_alias_tag and phpdoc_align rules will improve documentation readability and maintainability by:

  • Preventing the use of alias tags in PHPDoc
  • Ensuring consistent alignment of key documentation elements

However, these CS Fixer changes seem unrelated to the main PR objective of removing the Operations module. Consider splitting these changes into a separate PR for better change management.

database/migrations/2024_12_11_173633_cleanup_office_location.php (1)

30-44: Optimize table and foreign key creation in down method

Several improvements can be made to the down method:

  1. Match column types with referenced columns
  2. Add indexes for foreign keys
  3. Consolidate Schema::table calls

Apply this diff to optimize the down method:

 Schema::create('office_locations', function (Blueprint $table) {
     $table->id();
     $table->string('centre_name');
-    $table->integer('centre_head_id')->unsigned();
+    $table->unsignedBigInteger('centre_head_id')->index();
     $table->integer('capacity');
     $table->integer('current_people_count');
     $table->timestamps();
+    $table->foreign('centre_head_id')->references('id')->on('users');
 });
-Schema::table('office_locations', function (Blueprint $table) {
-    $table->foreign('centre_head_id')->references('id')->on('users');
-});
 Schema::table('code_trek_applicants', function (Blueprint $table) {
-    $table->unsignedBigInteger('centre_id')->nullable();
+    $table->unsignedBigInteger('centre_id')->nullable()->index();
     $table->foreign('centre_id')->references('id')->on('office_locations');
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d983b40 and e02b973.

⛔ Files ignored due to path filters (1)
  • composer.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • .github/workflows/coding-standards.yml (1 hunks)
  • .php-cs-fixer.php (1 hunks)
  • Modules/CodeTrek/Resources/views/index.blade.php (7 hunks)
  • app/Http/Controllers/HomeController.php (0 hunks)
  • composer.json (3 hunks)
  • database/migrations/2024_12_11_173633_cleanup_office_location.php (1 hunks)
  • resources/views/layouts/navbar.blade.php (0 hunks)
💤 Files with no reviewable changes (2)
  • resources/views/layouts/navbar.blade.php
  • app/Http/Controllers/HomeController.php
✅ Files skipped from review due to trivial changes (1)
  • .github/workflows/coding-standards.yml
🚧 Files skipped from review as they are similar to previous changes (2)
  • Modules/CodeTrek/Resources/views/index.blade.php
  • composer.json
🧰 Additional context used
🪛 GitHub Actions: Integration testing
database/migrations/2024_12_11_173633_cleanup_office_location.php

[error] 16-16: Migration failed: Can't DROP 'centre_id'; check that column/key exists in code_trek_applicants table

🔇 Additional comments (2)
database/migrations/2024_12_11_173633_cleanup_office_location.php (2)

1-8: LGTM! Class structure follows Laravel conventions.

The migration class is properly structured with necessary imports and follows Laravel's naming conventions.


14-21: Verify complete cleanup of office location dependencies

Since this PR aims to remove all office location dependencies, let's verify if all related tables are properly handled.

Run this script to check for any remaining references to office locations or centre_id:

✅ Verification successful

Office location cleanup is complete and correct

The migration properly handles all dependencies:

  • Removes foreign key from code_trek_applicants table
  • Drops the office_locations table
  • No other tables depend on office_locations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to office locations or centre_id in migrations and schema

# Check for any other tables referencing office_locations
echo "Checking for foreign keys referencing office_locations table..."
rg -l "references.*office_locations" database/migrations/

# Check for any remaining centre_id columns
echo "Checking for any remaining centre_id columns..."
rg -l "centre_id" database/migrations/

# Check for any other office location related tables
echo "Checking for any other office location related tables..."
rg "Schema::create.*office|location|centre" database/migrations/

Length of output: 3758

🧰 Tools
🪛 GitHub Actions: Integration testing

[error] 16-16: Migration failed: Can't DROP 'centre_id'; check that column/key exists in code_trek_applicants table

Comment on lines 16 to 21
Schema::table('code_trek_applicants', function (Blueprint $table) {
$table->dropForeign('centre_id');
$table->dropColumn('centre_id');
});
Schema::dropIfExists('office_locations');
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix foreign key drop to handle potential missing constraints

The migration is failing because:

  1. The foreign key constraint name is incorrect. Laravel uses the convention table_name_column_name_foreign
  2. The constraint might not exist in some environments

Apply this diff to make the migration more robust:

 Schema::table('code_trek_applicants', function (Blueprint $table) {
-    $table->dropForeign('centre_id');
+    // Drop foreign key if exists
+    $table->getConnection()
+          ->getDoctrineSchemaManager()
+          ->listTableForeignKeys('code_trek_applicants')
+          ->filter(fn($key) => $key->getLocalColumns() === ['centre_id'])
+          ->each(fn($key) => $table->dropForeign($key->getName()));
     $table->dropColumn('centre_id');
 });

This change:

  1. Uses Doctrine's schema manager to find existing foreign keys
  2. Drops any foreign key constraints referencing the centre_id column
  3. Makes the migration more resilient across different environments
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Schema::table('code_trek_applicants', function (Blueprint $table) {
$table->dropForeign('centre_id');
$table->dropColumn('centre_id');
});
Schema::dropIfExists('office_locations');
}
Schema::table('code_trek_applicants', function (Blueprint $table) {
// Drop foreign key if exists
$table->getConnection()
->getDoctrineSchemaManager()
->listTableForeignKeys('code_trek_applicants')
->filter(fn($key) => $key->getLocalColumns() === ['centre_id'])
->each(fn($key) => $table->dropForeign($key->getName()));
$table->dropColumn('centre_id');
});
Schema::dropIfExists('office_locations');
}
🧰 Tools
🪛 GitHub Actions: Integration testing

[error] 16-16: Migration failed: Can't DROP 'centre_id'; check that column/key exists in code_trek_applicants table

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (4)
Modules/HR/Observers/Recruitment/ApplicationRoundObserver.php (1)

Line range hint 9-9: Remove unused import

The SendApplicationRoundScheduled job is imported but never used in the code. This was also flagged by the pipeline.

Apply this diff to remove the unused import:

-use Modules\HR\Jobs\Recruitment\SendApplicationRoundScheduled;
🧰 Tools
🪛 GitHub Actions: Coding Standards

[warning] Unused import found: Modules\HR\Jobs\Recruitment\SendApplicationRoundScheduled

Modules/HR/Http/Controllers/Recruitment/ReportsController.php (3)

Line range hint 48-58: Extract data transformation logic to a service class.

The data transformation logic for chart preparation is duplicated across multiple methods (also seen in showReportCard).

Create a dedicated service:

class ChartDataTransformer
{
    public function transformApplicantData($records)
    {
        $data = [];
        foreach ($records as $row) {
            $data['label'][] = (new Carbon($row->date_created_at))->format('M d');
            $data['data'][] = (int) $row->count;
            $data['afterBody'][] = $this->getVerifiedApplicationsCount($row->date_created_at);
        }
        return $data;
    }
}

Line range hint 71-93: Avoid code duplication with showReportCard method.

The showReportCard method largely duplicates the logic from searchBydate. The only significant difference is the date range calculation.

Consider:

  1. Merging these methods
  2. Using a parameter to determine the date range
  3. Extracting common logic
public function getReportCard(Request $request, $useCustomRange = false)
{
    $dateRange = $useCustomRange 
        ? $this->getCustomDateRange($request)
        : $this->getDefaultDateRange();
    
    return $this->generateReport($dateRange);
}

Line range hint 94-117: Optimize database queries in jobWiseApplicationsGraph.

The method performs N+1 queries by iterating through jobs and making a separate count query for each.

Replace with a single efficient query:

public function jobWiseApplicationsGraph(Request $request)
{
    $query = Application::select('hr_job_id', \DB::raw('COUNT(*) as count'))
        ->groupBy('hr_job_id');
        
    if ($request->filled(['start_date', 'end_date'])) {
        $query->whereBetween('created_at', [$request->start_date, $request->end_date]);
    }
    
    $applicationCounts = $query->pluck('count', 'hr_job_id');
    // ... rest of the logic
}
🧹 Nitpick comments (4)
Modules/HR/Observers/Recruitment/ApplicationRoundObserver.php (1)

Line range hint 20-38: Consider refactoring for better separation of concerns

The observer is handling multiple responsibilities including status management, email notifications, and calendar events. Consider extracting these into dedicated services:

  1. Create an ApplicationRoundEmailService for email handling
  2. Move calendar event creation to a dedicated ApplicationRoundCalendarService
  3. Use dependency injection for these services

This would improve maintainability, testability, and adhere better to the Single Responsibility Principle.

Example refactoring:

class ApplicationRoundObserver
{
    private $emailService;
    private $calendarService;

    public function __construct(
        ApplicationRoundEmailService $emailService,
        ApplicationRoundCalendarService $calendarService
    ) {
        $this->emailService = $emailService;
        $this->calendarService = $calendarService;
    }

    public function created(ApplicationRound $applicationRound)
    {
        $applicationRound->updateIsLatestColumn();
        $applicationRound->load('application', 'scheduledPerson');
        $applicationRound->application->untag('need-follow-up');

        if ($this->shouldSendEmail($applicationRound)) {
            $this->emailService->sendInterviewScheduleEmail($applicationRound);
        }
    }
    // ... rest of the methods
}

Also applies to: 47-60, 65-86

🧰 Tools
🪛 GitHub Actions: Coding Standards

[warning] Unused import found: Modules\HR\Jobs\Recruitment\SendApplicationRoundScheduled

Modules/HR/Http/Controllers/Recruitment/ReportsController.php (2)

Line range hint 29-47: Consider extracting query logic to a dedicated repository.

The searchBydate method contains complex query logic mixed with controller responsibilities. This violates the Single Responsibility Principle.

Consider:

  1. Creating an ApplicantRepository class
  2. Moving the query logic there
  3. Injecting the repository into the controller

Example structure:

class ApplicantRepository
{
    public function getApplicantCountsByDateRange($startDate, $endDate)
    {
        return Applicant::select(
            \DB::raw('COUNT(*) as count'),
            \DB::raw('MONTHNAME(created_at) as month_created_at'),
            \DB::raw('DATE(created_at) as date_created_at')
        )
            ->wheredate('created_at', '>=', $startDate)
            ->wheredate('created_at', '<=', $endDate)
            ->groupBy('date_created_at', 'month_created_at')
            ->orderBy('date_created_at', 'ASC')
            ->get();
    }
}

Line range hint 118-196: Consider implementing caching for report data.

The rejection reasons and round-wise rejection data queries are potentially expensive and might be cacheable if real-time accuracy isn't critical.

Example implementation:

private function getRejectionReasons($startDate, $endDate)
{
    $cacheKey = "rejection_reasons_{$startDate}_{$endDate}";
    return Cache::remember($cacheKey, now()->addHours(1), function () use ($startDate, $endDate) {
        return HRRejectionReason::select(...)
            ->whereDate('created_at', '>=', $startDate)
            ->whereDate('created_at', '<=', $endDate)
            ->groupBy('reason_title')
            ->get();
    });
}
Modules/ProjectContract/Http/Controllers/ProjectContractController.php (1)

Line range hint 1-146: Consider splitting this controller to improve maintainability.

The controller is handling too many responsibilities:

  • Contract CRUD operations
  • Email notifications
  • Review management
  • Client response handling
  • Finance review process

This violates the Single Responsibility Principle and makes the code harder to maintain.

Consider splitting this into multiple controllers:

  1. ProjectContractCrudController - Basic CRUD operations
  2. ProjectContractReviewController - Review process
  3. ProjectContractFinanceController - Finance-related operations
  4. ProjectContractClientController - Client-specific operations

Additionally, consider these improvements:

  1. Add input validation using Laravel Form Requests
  2. Add proper exception handling
  3. Add return type hints
  4. Add PHPDoc blocks for better documentation
  5. Move email logic to dedicated notification classes using Laravel's notification system

Would you like me to provide a detailed example of how to refactor this controller?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b3c16cf and ea771b4.

📒 Files selected for processing (18)
  • .php-cs-fixer.php (2 hunks)
  • Modules/HR/Entities/Applicant.php (1 hunks)
  • Modules/HR/Entities/Application.php (1 hunks)
  • Modules/HR/Entities/Job.php (1 hunks)
  • Modules/HR/Http/Controllers/Recruitment/ApplicationController.php (1 hunks)
  • Modules/HR/Http/Controllers/Recruitment/ReportsController.php (1 hunks)
  • Modules/HR/Jobs/SendHiringMailJob.php (1 hunks)
  • Modules/HR/Listeners/AppointmentSlotMailSent.php (1 hunks)
  • Modules/HR/Listeners/FollowUpListener.php (1 hunks)
  • Modules/HR/Listeners/Recruitment/ApplicantEmailVerification.php (1 hunks)
  • Modules/HR/Listeners/Recruitment/AutoRespondApplicant.php (1 hunks)
  • Modules/HR/Listeners/Recruitment/CreateFirstApplicationRound.php (1 hunks)
  • Modules/HR/Listeners/Recruitment/UpdateJobRounds.php (1 hunks)
  • Modules/HR/Listeners/SendCustomApplicationMail.php (1 hunks)
  • Modules/HR/Observers/Recruitment/ApplicationRoundObserver.php (2 hunks)
  • Modules/HR/Observers/Recruitment/JobObserver.php (3 hunks)
  • Modules/ProjectContract/Http/Controllers/ProjectContractController.php (1 hunks)
  • app/Listeners/RemoveUserFromWebsite.php (1 hunks)
✅ Files skipped from review due to trivial changes (14)
  • Modules/HR/Jobs/SendHiringMailJob.php
  • Modules/HR/Listeners/Recruitment/CreateFirstApplicationRound.php
  • Modules/HR/Entities/Application.php
  • Modules/HR/Http/Controllers/Recruitment/ApplicationController.php
  • Modules/HR/Listeners/Recruitment/UpdateJobRounds.php
  • app/Listeners/RemoveUserFromWebsite.php
  • Modules/HR/Entities/Applicant.php
  • Modules/HR/Listeners/AppointmentSlotMailSent.php
  • Modules/HR/Observers/Recruitment/JobObserver.php
  • Modules/HR/Entities/Job.php
  • Modules/HR/Listeners/Recruitment/ApplicantEmailVerification.php
  • Modules/HR/Listeners/FollowUpListener.php
  • Modules/HR/Listeners/SendCustomApplicationMail.php
  • Modules/HR/Listeners/Recruitment/AutoRespondApplicant.php
🚧 Files skipped from review as they are similar to previous changes (1)
  • .php-cs-fixer.php
🧰 Additional context used
🪛 GitHub Actions: Coding Standards
Modules/HR/Observers/Recruitment/ApplicationRoundObserver.php

[warning] Unused import found: Modules\HR\Jobs\Recruitment\SendApplicationRoundScheduled

🔇 Additional comments (3)
Modules/HR/Observers/Recruitment/ApplicationRoundObserver.php (1)

16-16: LGTM: Improved PHPDoc formatting

The parameter documentation formatting has been standardized, improving consistency and adherence to PSR standards.

Also applies to: 43-43

🧰 Tools
🪛 GitHub Actions: Coding Standards

[warning] Unused import found: Modules\HR\Jobs\Recruitment\SendApplicationRoundScheduled

Modules/ProjectContract/Http/Controllers/ProjectContractController.php (2)

63-63: LGTM! Case sensitivity fix.

The correction from client::all() to Client::all() is appropriate as PHP class names are case-sensitive.


Line range hint 5-9: Verify dependencies after operations module removal.

Since this PR removes the operations module and office location dependencies, let's verify that the imported models (Client, Country) don't have any indirect dependencies on the removed components.

✅ Verification successful

Imports are clean and aligned with operations module removal

The imported models (Client and Country) have no dependencies on the removed operations module or office locations. The cleanup migrations confirm these dependencies have been properly removed from the database schema.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining references to office locations in the Client and Country models
echo "Checking Client model dependencies..."
rg -l "office_location|OfficeLocation|centre_id|center_id" "app/Models/Client.php"

echo "Checking Country model dependencies..."
rg -l "office_location|OfficeLocation|centre_id|center_id" "Modules/Client/Entities/Country.php"

# Check for any remaining operations module references
echo "Checking for operations module references..."
rg -l "Modules\\\\Operation|use Operation|operations?" "app/Models/Client.php" "Modules/Client/Entities/Country.php"

Length of output: 563


Script:

#!/bin/bash
# First, verify if the files exist
echo "Checking if files exist..."
fd -t f "Client.php" "app/Models"
fd -t f "Country.php" "Modules/Client"

# Search for broader patterns in these models
echo -e "\nChecking for operations and location related code..."
rg "(?i)(office|location|centre|center|operation)" -t php "app/Models/Client.php" "Modules/Client/Entities/Country.php" -C 2

# Check migrations for related columns
echo -e "\nChecking migrations..."
fd -e php -t f . "database/migrations" "Modules/Client/Database/Migrations" --exec rg "(?i)(office|location|centre|center|operation)"

# Look for relationship methods
echo -e "\nChecking for relationship methods..."
ast-grep --pattern 'public function $RELATION() {
  return $this->$$$;
}'

Length of output: 2334

@@ -26,7 +26,7 @@ public function index()

public function searchBydate(Request $req)
{
$req->report_start_date = $req->report_start_date ?? carbon::now()->startOfMonth() == $req->report_end_date = $req->report_end_date ?? Carbon::today();
$req->report_start_date = $req->report_start_date ?? Carbon::now()->startOfMonth() == $req->report_end_date = $req->report_end_date ?? Carbon::today();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix the logical error and improve readability in date assignment.

The current line has multiple issues:

  1. The comparison operator == is incorrectly used where an assignment was intended
  2. The single-line multiple assignment reduces readability
  3. The logic for default dates could be clearer

Replace with:

-        $req->report_start_date = $req->report_start_date ?? Carbon::now()->startOfMonth() == $req->report_end_date = $req->report_end_date ?? Carbon::today();
+        $req->report_start_date = $req->report_start_date ?? Carbon::now()->startOfMonth();
+        $req->report_end_date = $req->report_end_date ?? Carbon::today();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$req->report_start_date = $req->report_start_date ?? Carbon::now()->startOfMonth() == $req->report_end_date = $req->report_end_date ?? Carbon::today();
$req->report_start_date = $req->report_start_date ?? Carbon::now()->startOfMonth();
$req->report_end_date = $req->report_end_date ?? Carbon::today();

@rathorevaibhav rathorevaibhav merged commit 5b3c207 into master Jan 9, 2025
7 checks passed
@rathorevaibhav rathorevaibhav deleted the feat/operation_module_code_clean branch January 9, 2025 14:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants