Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- GitHub Copilot: # Code Analysis: upload_masterlist.php
- This PHP script handles the upload and processing of an Excel file containing employee data. The file is processed and the employee information is inserted into an `approval_table` database table. Here's how it works:
- ## Functionality Overview
- 1. The script uses PhpSpreadsheet library to read Excel files
- 2. It processes each row of the uploaded spreadsheet (skipping the header)
- 3. For each row, it extracts employee data and inserts it into the approval_table
- 4. It generates employee IDs and passwords when not provided
- 5. It validates data and handles date conversions from Excel format
- ## Key Components
- - **Initial Setup**: Error reporting, includes, and response structure
- - **Helper Functions**:
- - `generatePassword()`: Creates an 8-digit numeric password
- - `generateCompanyNum()`: Creates a unique employee ID number
- - `nullIfEmpty()`: Converts empty values to NULL
- - **File Upload Handling**: Validates that a file was uploaded
- - **Data Processing**: Row-by-row extraction of employee data
- - **Data Validation**: Email uniqueness check across multiple tables
- - **Date Conversion**: Handles Excel date formats and string dates
- - **Database Insertion**: Prepares and executes SQL to insert employee records
- ## Potential Problems
- 1. **Security Issues**:
- - No sanitization of input data before database insertion (relies solely on prepared statements)
- - No validation of file type before processing (could allow malicious files)
- - Simplified password generation that's predictable and insecure
- 2. **Date Handling Issues**:
- - The `convertDate()` function is defined inside a conditional block, potentially causing scope issues
- - Falls back to current date for invalid dates without clear warning
- 3. **Error Handling**:
- - Some errors only logged (not returned to user)
- - Inconsistent error reporting between console logs and response details
- - Missing validation for many fields before database insertion
- 4. **Data Integrity**:
- - No transaction handling for batch processing
- - No checks for required fields or data type validation
- - No validation of data format (email format, phone numbers, etc.)
- 5. **Performance Issues**:
- - No batch processing for large files
- - Each row requires a separate database query for email checking
- 6. **Code Structure**:
- - Inconsistent parameter binding (mixing different data types in a single prepared statement)
- - Long parameter list makes maintenance difficult
- - Nested try-catch blocks could be simplified
- 7. **Missing Features**:
- - No progress reporting for large files
- - Limited feedback on specific row insertion failures
- - No option to update existing records
- This script would benefit from improved validation, better error messaging, more robust security measures, and possibly refactoring into smaller, more focused functions.
- captione-bot: can this code be able to add new unique employees from a new masterlist file and add them to the table it should insert into
- GitHub Copilot: # Employee Upload Functionality Analysis
- Yes, the code is designed to add new unique employees from a masterlist Excel file into the `approval_table`. Here's how it works specifically for this purpose:
- ## The Uniqueness Check
- The script performs a uniqueness check based on employee email addresses:
- ```php
- // Check if email already exists
- $emailCheckStmt = $conn->prepare("
- SELECT emp_email FROM employee_table WHERE emp_email = ?
- UNION
- SELECT emp_email FROM approval_table WHERE emp_email = ?
- ");
- $emailCheckStmt->bind_param("ss", $emp_email, $emp_email);
- $emailCheckStmt->execute();
- $emailCheckStmt->store_result();
- if ($emailCheckStmt->num_rows > 0) {
- $response['details'][] = "Skipping Row $rowIndex: Email $emp_email already exists.";
- $emailCheckStmt->close();
- continue;
- }
- ```
- This check ensures:
- 1. The email doesn't exist in the `employee_table`
- 2. The email doesn't exist in the `approval_table`
- If an email already exists, that row is skipped, and the system continues processing the next employee.
- ## ID Generation
- For employees without company numbers, the code automatically generates one:
- ```php
- if (empty($emp_company_num)) {
- $emp_company_num = generateCompanyNum($conn);
- }
- ```
- The `generateCompanyNum()` function creates a unique ID in the format `EMP-YYYY-#########` where YYYY is the current year and ######### is a sequential number.
- ## Data Insertion
- If an employee is unique (based on email), their data is inserted into the `approval_table` with this statement:
- ```php
- $stmt = $conn->prepare("INSERT INTO approval_table (...) VALUES (...)");
- ```
- ## Conclusion
- This code can successfully add new unique employees from a masterlist file to the `approval_table`. However, be aware of these limitations:
- 1. **Uniqueness is only based on email** - If two employees have the same email but different names/details, one will be skipped
- 2. **No update functionality** - It can't update existing employee records, only add new ones
- 3. **No batch processing** - Each row is processed individually, which could be slow for large files
- If you need to update existing employees or check uniqueness based on multiple fields (like employee ID + name), the code would need to be modified.
- captione-bot: okay it actually goes through the approval table first. given the information i know how to diagnose my problem right now
- GitHub Copilot: ## Approval Table Process Understanding
- Yes, you're correct. This script actually processes the uploaded employee data into the `approval_table` first, not directly into the `employee_table`. This is important to understand for diagnosing your issue.
- The workflow appears to be:
- 1. Excel file is uploaded with employee data
- 2. Script checks if emails are unique across both tables:
- ```php
- SELECT emp_email FROM employee_table WHERE emp_email = ?
- UNION
- SELECT emp_email FROM approval_table WHERE emp_email = ?
- ```
- 3. If unique, it inserts the new employee into the `approval_table`
- 4. Presumably, there's a separate approval process (not shown in this code) that would later move approved records from `approval_table` to `employee_table`
- This two-step process allows for validation/approval before employees are officially added to the system.
- Common issues you might be experiencing:
- 1. **Records stuck in approval**: If employees appear in the approval table but not employee_table, they may need manual approval
- 2. **Duplicate detection**: If you're trying to re-upload employees and they're being skipped, it's because their emails already exist
- 3. **Missing data in application**: If your application queries only `employee_table` but new employees are only in `approval_table`, they won't appear
- 4. **Field mapping issues**: If some fields in your Excel don't match what the code expects, you may get partial or malformed data
- To diagnose effectively, check:
- - Are records being inserted into `approval_table` successfully?
- - Is there an approval mechanism that needs to be triggered?
- - Are there any error messages in your logs that provide more detail?
- captione-bot: our system actually consist of two applications - the HRIS and the payroll, and the payroll can be independent. since HRIS has the code for the approval, it leaves the independent payroll application's uploaded masterlist employees stuck at the approval table. can you give me any possible solutions for this?
- GitHub Copilot: # Solutions for Handling Masterlist Employees in Approval Table
- Since your system consists of two separate applications (HRIS and Payroll), with HRIS handling the approval process, you have a bottleneck where uploaded employees in the Payroll system are stuck in the approval table when Payroll operates independently. Here are potential solutions:
- ## Option 1: Auto-Approve for Payroll Module
- ```php
- // Add this at the end of the existing upload code before response echo
- if (isset($_POST['source']) && $_POST['source'] === 'payroll') {
- // Get all pending records
- $query = "SELECT * FROM approval_table WHERE emp_status = 'pending' OR emp_status IS NULL";
- $result = $conn->query($query);
- while ($employee = $result->fetch_assoc()) {
- // Insert into employee_table
- $insertStmt = $conn->prepare("INSERT INTO employee_table
- (emp_fname, emp_mname, emp_lname, /* ...all other fields... */)
- VALUES (?, ?, ?, /* ...all other values... */)");
- // Bind all parameters from $employee array
- $insertStmt->bind_param("sss...s",
- $employee['emp_fname'],
- $employee['emp_mname'],
- $employee['emp_lname'],
- // ... bind all other fields
- );
- $insertStmt->execute();
- // Update approval status
- $updateStmt = $conn->prepare("UPDATE approval_table SET emp_status = 'approved' WHERE id = ?");
- $updateStmt->bind_param("i", $employee['id']);
- $updateStmt->execute();
- }
- $response['message'] .= " Employees automatically approved for payroll system.";
- }
- ```
- ## Option 2: Add Direct Employee Import Function for Payroll
- Create a separate upload script specifically for the payroll system that bypasses the approval table:
- ```php
- <?php
- // Similar code to upload_masterlist.php but inserts directly to employee_table
- require 'vendor/autoload.php';
- use PhpOffice\PhpSpreadsheet\IOFactory;
- use PhpOffice\PhpSpreadsheet\Shared\Date;
- include '../db_connection.php';
- // ...existing functions and validations...
- // Remove the approval table check from the email uniqueness check
- $emailCheckStmt = $conn->prepare("SELECT emp_email FROM employee_table WHERE emp_email = ?");
- $emailCheckStmt->bind_param("s", $emp_email);
- // Skip approval table, insert directly to employee_table
- $stmt = $conn->prepare("INSERT INTO employee_table (/* fields */) VALUES (/* values */)");
- // ...bind parameters and execute...
- ```
- ## Option 3: Scheduled Task to Approve Records
- Create a cron job or scheduled task that automatically approves records after a certain time:
- ```php
- <?php
- include '../db_connection.php';
- // Get records older than X hours
- $hours = 24; // Configure as needed
- $query = "SELECT * FROM approval_table WHERE
- created_at < DATE_SUB(NOW(), INTERVAL $hours HOUR) AND
- (emp_status = 'pending' OR emp_status IS NULL)";
- $result = $conn->query($query);
- $count = 0;
- while ($employee = $result->fetch_assoc()) {
- // Insert into employee_table and update approval status
- // Similar to Option 1
- $count++;
- }
- echo "Auto-approved $count employee records";
- ```
- ## Option 4: Database View Solution
- Create a database view that combines both tables for the payroll system:
- ```sql
- CREATE VIEW employee_combined_view AS
- SELECT * FROM employee_table
- UNION
- SELECT * FROM approval_table WHERE emp_status = 'pending' OR emp_status IS NULL;
- ```
- Then modify your payroll application to use this view instead of just the employee_table.
- ## Option 5: Add Configuration Parameter
- Add a configuration setting that determines whether the approval process is required:
- ```php
- // Add to the beginning of upload_masterlist.php
- $config = include '../config.php';
- $requireApproval = $config['require_employee_approval'] ?? true;
- // Then modify the insert logic
- if ($requireApproval) {
- // Insert into approval_table as currently done
- } else {
- // Insert directly to employee_table
- }
- ```
- ## Recommendation
- Option 1 is likely the most straightforward solution as it allows you to maintain your current code structure but add a parameter to skip approval when needed for the payroll system. You simply need to modify your front-end to pass a 'source' parameter when uploading from the payroll module.
- Each solution has different implications for your data integrity and workflow. Choose based on your specific business rules and how strictly you want to enforce the approval process.
- captione-bot: would option one have implications when i use the payroll with the hris integrated?
- GitHub Copilot: # Implications of Option 1 When Using Integrated HRIS and Payroll
- Yes, Option 1 (auto-approval for payroll module) would have several implications when you operate with both systems integrated:
- ## Potential Issues with Integration
- 1. **Duplicate Approval Processing**:
- - When payroll auto-approves employees, and HRIS later processes the same records, you might get conflicting states or duplicate processing attempts
- 2. **Approval Workflow Bypass**:
- - Auto-approval circumvents any validation checks, approver assignments, or multi-stage approval workflows in the HRIS system
- - Any custom business rules enforced during HRIS approval would be skipped
- 3. **Data Inconsistency**:
- - Records approved through payroll might have different quality/validation standards than those approved through HRIS
- - Could result in inconsistent employee data between systems
- 4. **Audit Trail Problems**:
- - Auto-approved records wouldn't have proper approval audit trails
- - Compliance issues if your system requires documented approval processes
- ## Better Solutions for Integrated Environment
- If you run both systems together sometimes and separately other times, consider these alternative approaches:
- ### 1. System Mode Parameter
- ```php
- // At the beginning of upload_masterlist.php
- $operatingMode = $_POST['system_mode'] ?? 'integrated'; // Options: 'integrated', 'payroll_only'
- // Then near the end of your processing logic
- if ($operatingMode === 'payroll_only') {
- // Copy from approval_table to employee_table with a 'payroll_auto_approved' flag
- // This allows HRIS to see which records were auto-approved when integrated
- }
- ```
- ### 2. Configuration-Based Approach
- Create a configuration file that defines the environment:
- ```php
- // In config.php
- return [
- 'environment' => getenv('APP_ENV') ?: 'integrated', // 'integrated', 'hris_only', 'payroll_only'
- 'auto_approve_payroll' => getenv('APP_ENV') === 'payroll_only'
- ];
- // Then in upload_masterlist.php
- $config = include '../config.php';
- if ($config['auto_approve_payroll']) {
- // Auto-approve logic
- }
- ```
- ### 3. Database Flag with Manual Review
- ```php
- // Add a source column to approval_table
- // When inserting:
- $source = isset($_POST['source']) ? $_POST['source'] : 'hris';
- // Include $source in your INSERT statement
- // Add a UI element in HRIS that shows payroll-sourced employees for expedited review
- // This maintains approval workflow but highlights records needing quick approval
- ```
- ## Recommendation for Integrated Environment
- For an environment that operates in both integrated and standalone modes, I'd recommend:
- 1. Add a `source` column to your `approval_table` to track where records originated
- 2. Create a configuration setting that determines the operating mode
- 3. Add an expedited approval process in HRIS for payroll-sourced records
- 4. Implement a notification system to alert HRIS admins when payroll adds employees
- This approach maintains data integrity and approval workflows while addressing the immediate need to use both systems independently when required.
- captione-bot: would a separate upload_masterlist file alleviate those problems?
- GitHub Copilot: # Separate Upload File for Payroll - Analysis
- Yes, creating a separate `payroll_upload_masterlist.php` file for the payroll system would alleviate most of the integration issues. This approach (similar to Option 2 I mentioned earlier) has several advantages:
- ## Benefits of Separate Upload Files
- 1. **Clear Separation of Concerns**:
- - Each system has its own dedicated upload functionality
- - No need for complex conditional logic in a single file
- 2. **Independent Operation**:
- - Payroll system can run independently without approval bottlenecks
- - HRIS approval workflow remains intact when used
- 3. **Avoids Integration Conflicts**:
- - No risk of duplicate processing or approval conflicts
- - Each system follows its own defined workflow
- 4. **Simplified Maintenance**:
- - Changes to one system's upload process won't affect the other
- - Easier to debug issues specific to each system
- ## Implementation Approach
- The payroll version would be similar to your current file but with these key differences:
- ```php
- <?php
- // Similar header, includes, and functions as upload_masterlist.php
- try {
- // File processing and validation code (same as original)
- // Process each row (similar to original)
- foreach ($worksheet->getRowIterator() as $rowIndex => $row) {
- // Extract data from row (same as original)
- // Different email check - only check employee_table
- $emailCheckStmt = $conn->prepare("SELECT emp_email FROM employee_table WHERE emp_email = ?");
- $emailCheckStmt->bind_param("s", $emp_email);
- // Rest of validation code
- // Different insertion - direct to employee_table instead of approval_table
- $stmt = $conn->prepare("INSERT INTO employee_table (
- emp_fname, emp_mname, emp_lname, /* same fields */
- ) VALUES (/* same values */)");
- // Same binding and execution code
- }
- $response['status'] = 'success';
- $response['message'] = 'Employees added directly to system.';
- } catch (Exception $e) {
- // Error handling
- }
- echo json_encode($response);
- ```
- ## Important Considerations
- 1. **Code Duplication**:
- - You'll have duplicate code between files - consider extracting common functions to a shared file
- - Example: `include 'employee_upload_functions.php';`
- 2. **Database Consistency**:
- - Ensure both files generate employee IDs consistently
- - Your `generateCompanyNum()` function already handles this well
- 3. **User Interface**:
- - Provide clear instructions in the UI about which upload option to use
- - Consider adding system-specific validation rules if needed
- 4. **Future Maintenance**:
- - If you change field requirements, you'll need to update both files
- - Documentation is important to remember which file does what
- This approach is clean, straightforward, and maintains the independence of both systems while allowing them to work together when needed. It's likely the best solution given your requirement for independent operation of the payroll system.
- captione-bot: okay. ill probably just do the separate file solution. the considerations are acceptable. can you generate the solution as a whole code? I will paste it on a different file.
- GitHub Copilot: # Payroll Employee Upload Solution
- Here's the complete `payroll_upload_masterlist.php` file for direct employee insertion from the payroll system:
- ```php
- <?php
- // Enable error reporting for debugging
- error_reporting(E_ALL);
- ini_set('display_errors', 1);
- require 'vendor/autoload.php';
- use PhpOffice\PhpSpreadsheet\IOFactory;
- use PhpOffice\PhpSpreadsheet\Shared\Date;
- include '../db_connection.php';
- $response = [
- 'status' => 'error',
- 'message' => '',
- 'details' => []
- ];
- function generatePassword($length = 8) {
- return str_pad(rand(0, 99999999), 8, '0', STR_PAD_LEFT);
- }
- function generateCompanyNum($conn) {
- $year = date('Y');
- $query = "
- SELECT MAX(emp_company_num) as max_num FROM (
- SELECT emp_company_num FROM employee_table WHERE emp_company_num LIKE 'EMP-$year-%'
- UNION ALL
- SELECT emp_company_num FROM approval_table WHERE emp_company_num LIKE 'EMP-$year-%'
- ) AS combined";
- $result = $conn->query($query);
- if ($result) {
- $row = $result->fetch_assoc();
- if ($row['max_num']) {
- $last_num = (int)substr($row['max_num'], -9);
- $new_num = str_pad($last_num + 1, 9, '0', STR_PAD_LEFT);
- } else {
- $new_num = '000000001';
- }
- return "EMP-$year-$new_num";
- }
- return null;
- }
- function nullIfEmpty($value) {
- return empty($value) ? null : $value;
- }
- try {
- if (!isset($_FILES['file'])) {
- throw new Exception("No file uploaded.");
- }
- $file = $_FILES['file']['tmp_name'];
- if (!file_exists($file)) {
- throw new Exception("Error: File not found. Please try uploading again.");
- }
- try {
- $spreadsheet = IOFactory::load($file);
- } catch (Exception $e) {
- throw new Exception("Error loading spreadsheet: " . $e->getMessage());
- }
- $worksheet = $spreadsheet->getActiveSheet();
- $insertCount = 0;
- foreach ($worksheet->getRowIterator() as $rowIndex => $row) {
- if ($rowIndex === 1) continue; // Skip header row
- $rowData = [];
- foreach ($row->getCellIterator() as $cell) {
- $rowData[] = $cell->getValue();
- }
- if (count($rowData) < 38) {
- error_log("Row $rowIndex has insufficient data fields.");
- continue;
- }
- list($emp_fname, $emp_mname, $emp_lname, $emp_dob, $emp_gender, $emp_nationality,
- $emp_marital_status, $emp_position, $emp_company_num, $emp_email, $emp_number,
- $emp_zip, $unique_manager, $unique_department, $sss, $emp_password, $emp_address,
- $emp_date_hired, $emp_end_date, $emp_type, $emp_salary, $emp_allowance, $emp_status,
- $pag_ibig, $tin_number, $philhealth, $account_number, $emp_emergency_name,
- $emp_emergency_number, $emp_emergency_relationship, $payroll_type, $date_regularized,
- $previous_employer_name, $previous_tin_number, $previous_registered_address,
- $previous_zip_code, $prev_taxable_income, $prev_tax_withheld, $other_id
- ) = $rowData;
- // Log raw values
- error_log("Row $rowIndex - Raw Data: emp_fname=$emp_fname, emp_lname=$emp_lname, emp_dob=$emp_dob, emp_date_hired=$emp_date_hired, emp_end_date=$emp_end_date");
- // Check if email already exists only in employee_table (skip approval_table check)
- $emailCheckStmt = $conn->prepare("SELECT emp_email FROM employee_table WHERE emp_email = ?");
- $emailCheckStmt->bind_param("s", $emp_email);
- $emailCheckStmt->execute();
- $emailCheckStmt->store_result();
- if ($emailCheckStmt->num_rows > 0) {
- $response['details'][] = "Skipping Row $rowIndex: Email $emp_email already exists.";
- $emailCheckStmt->close();
- continue;
- }
- $emailCheckStmt->close();
- // Convert empty values to NULL
- $emp_mname = nullIfEmpty($emp_mname);
- $emp_end_date = nullIfEmpty($emp_end_date);
- $pag_ibig = nullIfEmpty($pag_ibig);
- $philhealth = nullIfEmpty($philhealth);
- $tin_number = nullIfEmpty($tin_number);
- $account_number = nullIfEmpty($account_number);
- $emp_salary = nullIfEmpty($emp_salary);
- $emp_allowance = nullIfEmpty($emp_allowance);
- $emp_status = nullIfEmpty($emp_status);
- $emp_type = nullIfEmpty($emp_type);
- // Handle date conversions
- if (!function_exists('convertDate')) {
- function convertDate($date, $rowIndex, $fieldName) {
- if (!empty($date)) {
- if (is_numeric($date)) {
- return Date::excelToDateTimeObject($date)->format('Y-m-d');
- } else {
- $timestamp = strtotime($date);
- if ($timestamp !== false) {
- return date("Y-m-d", $timestamp);
- } else {
- error_log("Invalid date format at Row $rowIndex: $fieldName=" . var_export($date, true));
- return date("Y-m-d");
- }
- }
- }
- return null;
- }
- }
- $emp_dob = convertDate($emp_dob, $rowIndex, 'emp_dob');
- $emp_date_hired = convertDate($emp_date_hired, $rowIndex, 'emp_date_hired') ?? date("Y-m-d");
- $emp_end_date = convertDate($emp_end_date, $rowIndex, 'emp_end_date');
- $date_regularized = convertDate($date_regularized, $rowIndex, 'date_regularized');
- if (empty($emp_company_num)) {
- $emp_company_num = generateCompanyNum($conn);
- }
- if (empty($emp_password)) {
- $emp_password = generatePassword();
- }
- // Insert directly into employee_table instead of approval_table
- $stmt = $conn->prepare("INSERT INTO employee_table (
- emp_fname, emp_mname, emp_lname, emp_dob, emp_gender, emp_nationality, emp_marital_status,
- emp_position, emp_company_num, emp_email, emp_number, emp_zip, employ_manager, employ_dept, sss,
- emp_password, emp_address, emp_date_hired, emp_end_date, emp_type, emp_salary, emp_allowance, emp_status,
- pag_ibig, tin_number, philhealth, account_number, emp_emergency_name, emp_emergency_number, emp_emergency_relationship,
- payroll_type, date_regularized, previous_employer_name, previous_tin_number, previous_registered_address,
- previous_zip_code, prev_taxable_income, prev_tax_withheld, other_id
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
- if (!$stmt) {
- throw new Exception("Error preparing statement: " . $conn->error);
- }
- $stmt->bind_param(
- "sssssssisssiiissssssddssssssssssssssdds",
- $emp_fname, $emp_mname, $emp_lname, $emp_dob, $emp_gender, $emp_nationality, $emp_marital_status,
- $emp_position,
- $emp_company_num, $emp_email, $emp_number,
- $emp_zip, $unique_manager, $unique_department,
- $sss, $emp_password, $emp_address, $emp_date_hired, $emp_end_date, $emp_type,
- $emp_salary, $emp_allowance,
- $emp_status,
- $pag_ibig, $tin_number, $philhealth, $account_number, $emp_emergency_name, $emp_emergency_number, $emp_emergency_relationship, $payroll_type, $date_regularized, $previous_employer_name, $previous_tin_number, $previous_registered_address,
- $previous_zip_code, $prev_taxable_income, $prev_tax_withheld,
- $other_id
- );
- try {
- $stmt->execute();
- $insertCount++;
- $response['details'][] = "Row $rowIndex: Employee $emp_fname $emp_lname added successfully.";
- } catch (Exception $e) {
- $response['details'][] = "Error on Row $rowIndex: " . $e->getMessage();
- }
- $stmt->close();
- }
- $response['status'] = 'success';
- $response['message'] = "Upload complete. $insertCount employees added directly to system.";
- } catch (Exception $e) {
- $response['message'] = $e->getMessage();
- }
- echo json_encode($response);
- $conn->close();
- exit;
- ```
- ## Key Differences from Original File
- 1. **Modified Email Check**: Only checks `employee_table` (skips approval_table)
- ```php
- $emailCheckStmt = $conn->prepare("SELECT emp_email FROM employee_table WHERE emp_email = ?");
- ```
- 2. **Direct Insertion**: Inserts directly into `employee_table` instead of `approval_table`
- ```php
- $stmt = $conn->prepare("INSERT INTO employee_table (...) VALUES (...)");
- ```
- 3. **Improved Feedback**: Reports successful insertions and keeps track of count
- ```php
- $insertCount++;
- $response['details'][] = "Row $rowIndex: Employee $emp_fname $emp_lname added successfully.";
- ```
- 4. **Better Error Handling**: Wraps execution in try-catch to continue processing after errors
- ```php
- try {
- $stmt->execute();
- // Success handling
- } catch (Exception $e) {
- $response['details'][] = "Error on Row $rowIndex: " . $e->getMessage();
- }
- ```
- This implementation will directly add employees to your system, bypassing the approval process, while maintaining all the same validation logic and data formatting from your original script.
- Similar code found with 2 license types
- captione-bot: great. now, the upload_masterlist.php is a button within a main page, the add_employee.php which is also used by both independent and integrated hris + payroll applications. is there a flag we can use to condition what upload_masterlist code it should use?
- GitHub Copilot: # Using a Flag to Condition Upload Masterlist Behavior
- Yes, you can implement a flag in your upload process to determine which version of the code to use based on the context (independent payroll vs integrated HRIS+payroll). Here are two approaches:
- ## Option 1: Query Parameter in Upload Button
- Modify your "Upload Masterlist" button to include a parameter that identifies the source:
- ```javascript
- function showUploadModal() {
- // Get the current system mode
- const isPayrollOnly = <?php echo $_SESSION['access'] === 'Payroll' && !isset($_SESSION['integrated_mode']) ? 'true' : 'false'; ?>;
- Swal.fire({
- title: 'Upload Masterlist',
- text: 'Please select the masterlist file to upload:',
- input: 'file',
- inputAttributes: {
- 'accept': '.xlsx, .xls' // Accept Excel files
- },
- showCancelButton: true,
- confirmButtonText: 'Upload',
- cancelButtonText: 'Cancel',
- preConfirm: (file) => {
- if (!file) {
- Swal.showValidationMessage('Please select a file to upload');
- }
- return file;
- }
- }).then((result) => {
- if (result.isConfirmed) {
- uploadFile(result.value, isPayrollOnly);
- }
- });
- }
- function uploadFile(file, isPayrollOnly) {
- const formData = new FormData();
- formData.append('file', file);
- formData.append('mode', isPayrollOnly ? 'payroll_only' : 'integrated');
- $.ajax({
- url: 'upload_masterlist.php',
- type: 'POST',
- data: formData,
- processData: false,
- contentType: false,
- success: function(response) {
- // Your existing success handler
- },
- error: function(xhr, status, error) {
- // Your existing error handler
- }
- });
- }
- ```
- Then in your upload_masterlist.php, check for this parameter:
- ```php
- // At the beginning of upload_masterlist.php
- $mode = isset($_POST['mode']) ? $_POST['mode'] : 'integrated';
- $isPayrollOnly = ($mode === 'payroll_only');
- // Then later in your code, when inserting:
- if ($isPayrollOnly) {
- // Direct insertion to employee_table for independent payroll
- $stmt = $conn->prepare("INSERT INTO employee_table (/* fields */) VALUES (/* values */)");
- } else {
- // Original code path - insert into approval_table for HRIS workflow
- $stmt = $conn->prepare("INSERT INTO approval_table (/* fields */) VALUES (/* values */)");
- }
- ```
- ## Option 2: Configuration-Based Approach
- Create a configuration setting in your application that determines the behavior:
- ```php
- // In your upload_masterlist.php
- include '../db_connection.php';
- include '../config.php'; // Include your configuration file
- // Check the configuration or session to determine mode
- $isPayrollOnly = false;
- // Option 1: Check from configuration
- if (isset($config['system_mode']) && $config['system_mode'] === 'payroll_only') {
- $isPayrollOnly = true;
- }
- // Option 2: Check from session
- if (isset($_SESSION['access']) && $_SESSION['access'] === 'Payroll' && !isset($_SESSION['integrated_mode'])) {
- $isPayrollOnly = true;
- }
- // Later in your code:
- if ($isPayrollOnly) {
- // Insert directly to employee_table
- $targetTable = "employee_table";
- } else {
- // Insert to approval_table
- $targetTable = "approval_table";
- }
- // Use dynamic table name in your INSERT statement
- $stmt = $conn->prepare("INSERT INTO $targetTable (/* fields */) VALUES (/* values */)");
- ```
- ## Implementation for Your Specific Case
- Since you want to keep the code cleaner and avoid extensive conditional logic, here's how I'd implement it in your specific scenario:
- ```php
- // At the beginning of upload_masterlist.php
- $isPayrollOnly = false;
- // Determine if we're in payroll-only mode
- if (isset($_POST['system_mode']) && $_POST['system_mode'] === 'payroll_only') {
- $isPayrollOnly = true;
- } else if (isset($_SESSION['access']) && $_SESSION['access'] === 'Payroll' && !isset($_SESSION['integrated_mode'])) {
- $isPayrollOnly = true;
- }
- // Then, when executing the insertion:
- if ($isPayrollOnly) {
- // Direct insertion to employee_table
- $stmt = $conn->prepare("INSERT INTO employee_table (
- emp_fname, emp_mname, emp_lname, /* ...other fields... */
- ) VALUES (?, ?, ?, /* ...other placeholders... */)");
- // Same binding as before
- $stmt->bind_param("sssssssisssiiissssssddssssssssssssssdds", /* ...your parameters... */);
- // Execute and provide appropriate feedback
- if ($stmt->execute()) {
- $response['details'][] = "Row $rowIndex: Employee $emp_fname $emp_lname added directly to system.";
- }
- } else {
- // Original behavior - insert into approval_table
- $stmt = $conn->prepare("INSERT INTO approval_table (
- emp_fname, emp_mname, emp_lname, /* ...other fields... */
- ) VALUES (?, ?, ?, /* ...other placeholders... */)");
- // Same binding as before
- $stmt->bind_param("sssssssisssiiissssssddssssssssssssssdds", /* ...your parameters... */);
- // Execute and provide appropriate feedback
- if ($stmt->execute()) {
- $response['details'][] = "Row $rowIndex: Employee $emp_fname $emp_lname submitted for approval.";
- }
- }
- ```
- This approach lets you use the same file but conditionally change the behavior based on the mode, which is cleaner than having separate files with duplicated code.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement