| Server IP : 13.126.101.145 / Your IP : 216.73.217.37 Web Server : Apache/2.4.52 (Ubuntu) System : Linux ip-11-115-0-196 6.8.0-1039-aws #41~22.04.1-Ubuntu SMP Thu Sep 11 10:54:48 UTC 2025 x86_64 User : www-data ( 33) PHP Version : 8.3.17 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /var/www/html/rentals_updated/wp-content/plugins/work-order/ |
Upload File : |
<?php
// Add Region and Location Dropdowns to the WooCommerce Order Admin Edit Page (Same Line)
add_action( 'woocommerce_admin_order_data_after_order_details', 'add_region_and_location_to_order_page' );
function add_region_and_location_to_order_page( $order ) {
// Only display the fields if the order status is "wc-opassigned"
// Get the current order status label
$status_label = wc_get_order_status_name( $order->get_status() );
// Only display the fields if the order status label is "Operator Assigned"
if ( $status_label !== 'Operator Assigned' ) {
return;
}
// Get the saved region and location values, if available
$selected_region = get_post_meta( $order->get_id(), 'order_region', true );
$selected_location = get_post_meta( $order->get_id(), 'order_location', true );
$min_monthly_hours = get_post_meta( $order->get_id(), 'min_monthly_hours', true );
?>
<div class="form-field form-field-wide wc-customer-user">
<div class="custom-region-location-fields">
<!-- Region Dropdown -->
<p class="form-field form-field-wide">
<label for="order_region"><?php _e( 'Region', 'woocommerce' ); ?></label>
<input type="text" id="order_region" name="order_region" value="<?php echo esc_attr( $selected_region ); ?>" readonly>
</p>
<!-- Location Dropdown -->
<p class="form-field form-field-wide">
<label for="order_location"><?php _e( 'Location', 'woocommerce' ); ?></label>
<input type="text" id="order_location" name="order_location" value="<?php echo esc_attr( $selected_location ); ?>" readonly>
</p>
<!-- Min Monthly Hours Field -->
<div class="form-field form-field-wide">
<label for="min_monthly_hours"><?php _e( 'Min Monthly Hours', 'woocommerce' ); ?></label>
<input type="number" id="min_monthly_hours" name="min_monthly_hours" value="<?php echo esc_attr( $min_monthly_hours ); ?>" oninput="this.value = this.value < 0 ? 0 : this.value;" required/>
<div id="min_monthly_hours_error" style="color: red; display: none; margin-top: 5px;">
<?php _e( 'This field is required.', 'woocommerce' ); ?>
</div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
// Define the locations based on region
var locations = <?php echo json_encode( $locations ); ?>;
// On region change, update the location options
$('#order_region').change(function() {
var selectedRegion = $(this).val();
var $locationSelect = $('#order_location');
// Clear the current location options
$locationSelect.empty();
$locationSelect.append('<option value=""><?php _e( 'Select a Location', 'woocommerce' ); ?></option>');
// Populate the location options based on the selected region
if (selectedRegion && locations[selectedRegion]) {
locations[selectedRegion].forEach(function(location) {
$locationSelect.append('<option value="' + location + '">' + location + '</option>');
});
}
});
});
</script>
<style>
/* Style to display Region and Location on the same line */
.custom-region-location-fields {
display: flex;
gap: 20px; /* Adjust gap between the fields */
}
.custom-region-location-fields .form-field {
flex: 1; /* Make both fields take equal width */
}
.custom-region-location-fields select {
width: 100%; /* Ensure dropdown takes full width */
}
</style>
<?php
}
// Save the Region and Location fields when the order is updated
add_action( 'woocommerce_process_shop_order_meta', 'save_region_and_location_fields', 45, 2 );
function save_region_and_location_fields( $post_id, $post ) {
$region = isset( $_POST['order_region'] ) ? sanitize_text_field( $_POST['order_region'] ) : '';
$location = isset( $_POST['order_location'] ) ? sanitize_text_field( $_POST['order_location'] ) : '';
$min_monthly_hours = isset( $_POST['min_monthly_hours'] ) ? intval( $_POST['min_monthly_hours'] ) : 0;
update_post_meta( $post_id, '_region', $region );
update_post_meta( $post_id, '_location', $location );
update_post_meta( $post_id, '_min_monthly_hours', $min_monthly_hours );
}
// Add "Create Work Order" button next to "Add Order" at the top of the order edit page
add_action('admin_head', 'add_create_work_order_button_at_top');
function add_create_work_order_button_at_top() {
global $pagenow, $post;
// Ensure we are on the Edit Order screen in WooCommerce
if ($pagenow === 'post.php' && isset($post->post_type) && $post->post_type === 'shop_order') {
// Get the current order (post) ID
$order_id = $post->ID;
// Get the current order status label
$status_label = wc_get_order_status_name(get_post_status($order_id));
// Only display the "Create Work Order" button if the order status is "Operator Assigned"
if ($status_label === 'Operator Assigned') {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
// Add "Create Work Order" button next to "Add Order" button
var createWorkOrderButton = '<a href="#" class="page-title-action create-work-order-button"><?php _e("Create Work Order", "woocommerce"); ?></a>';
var minMonthlyHoursInput = document.getElementById('min_monthly_hours');
var errorSpan = document.getElementById('min_monthly_hours_error');
$('.wrap .page-title-action').after(createWorkOrderButton);
// Handle click event for "Create Work Order" button
$('.create-work-order-button').on('click', function(e) {
e.preventDefault(); // Prevent default behavior of the link
var button = $(this);
// Check if the button is already disabled
if (button.prop('disabled')) {
return; // Exit if button is disabled
}
if (!minMonthlyHoursInput.value) {
errorSpan.style.display = 'inline'; // Show error message
return; // Exit the function
} else {
errorSpan.style.display = 'none'; // Hide error message
}
minMonthlyHoursInput.addEventListener('input', function() {
if (minMonthlyHoursInput.value) {
errorSpan.style.display = 'none';
}
});
// Check if the required fields are filled
var region = $('#order_region').val();
var location = $('#order_location').val();
var minMonthlyHours = $('#min_monthly_hours').val();
var start_date = $('#start_date').val(); // Add start date field
var end_date = $('#end_date').val();
if (!region || !location || !minMonthlyHours) {
alert('Please fill in all required fields: Region, Location, and Min Monthly Hours.');
return; // Exit the function
}
// Disable the button to prevent multiple clicks
button.prop('disabled', true);
// Proceed to create work order via AJAX
$.ajax({
type: 'POST',
url: workOrderData.ajax_url,
data: {
action: 'create_work_order',
order_id: <?php echo $order_id; ?>,
region: region,
location: location,
min_monthly_hours: minMonthlyHours,
start_date: start_date,
end_date: end_date
},
success: function(response) {
if (response.success) {
alert(response.data); // Success message
// Redirect to the Work Orders page
window.location.href = '<?php echo admin_url('admin.php?page=work_orders'); ?>';
} else {
alert('Error: ' + response.data); // Error message
}
},
error: function(xhr, status, error) {
alert('An AJAX error occurred: ' + error); // Error handling
},
complete: function() {
// Re-enable the button after the request is complete
button.prop('disabled', false);
}
});
});
});
</script>
<?php
}
}
}
add_filter('gettext', function($translated_text, $original_text, $domain) {
if ($original_text === 'Create Work Order') {
return 'Create Work Order';
}
return $translated_text;
}, 10, 3);
// Enqueue jQuery and AJAX scripts
add_action('admin_enqueue_scripts', 'enqueue_custom_admin_script');
function enqueue_custom_admin_script() {
wp_enqueue_script('jquery');
wp_localize_script('jquery', 'workOrderData', array(
'ajax_url' => admin_url('admin-ajax.php'),
// No need for order_id here, it's passed inline in the button script
));
}
// AJAX handler to create a work order
add_action('wp_ajax_create_work_order', 'create_work_order');
function create_work_order() {
// Check user capabilities (optional)
if (!current_user_can('manage_options')) {
wp_send_json_error('You do not have permission to perform this action.');
}
// Retrieve posted data
$order_id = intval($_POST['order_id']);
$region = sanitize_text_field($_POST['region']);
$location = sanitize_text_field($_POST['location']);
$min_monthly_hours = intval($_POST['min_monthly_hours']);
// Fetch the work order start and end dates from the request
// Retrieve start and end dates
$start_date = sanitize_text_field($_POST['start_date']);
$end_date = sanitize_text_field($_POST['end_date']);
// Fetch user ID and username
$user_id = get_current_user_id();
$user_info = get_userdata($user_id);
// $user_name = $user_info->user_login;
// Fetch product names from the order
$order = wc_get_order($order_id);
// Fetch customer name from order (billing name)
$customer_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
$product_names = [];
$product_skus = [];
foreach ($order->get_items() as $item_id => $item) {
$product = $item->get_product(); // Get the product object
if ($product) {
$product_names[] = $product->get_name(); // Get the product name
$sku = get_post_meta($product->get_id(), '_sku', true);
if ($sku) {
$product_skus[] = $sku; // Store the SKU
}
}
}
// Convert product names to a comma-separated string
$equipement_name = implode(', ', $product_names);
$equip_asset_id = implode(', ', $product_skus);
// Fetch the order total from postmeta
$order_total = get_post_meta($order_id, '_order_total', true); // Get the total amount of the order
// Call the function to insert the work order into the database
$inserted_id = insert_work_order($order_id, $user_id, $customer_name, $region, $location, $min_monthly_hours, $equipement_name, $start_date, $end_date,$order_total, $equip_asset_id);
if ($inserted_id) {
// Update the order status to "Work Order Generated"
$order->update_status('wc-work_order');
// Send success response
wp_send_json_success('Work order created successfully with ID: ' . $inserted_id);
} else {
wp_send_json_error('Failed to create work order. Error: ' . print_r($inserted_id, true));
}
wp_die(); // Properly end the AJAX request
}
// Function to insert a new work order into the wp_work_orders table
function insert_work_order($order_id, $user_id, $customer_name, $region, $location, $min_monthly_hours, $equipement_name, $start_date, $end_date, $order_total, $equip_asset_id) {
global $wpdb;
// Example of work order data to be inserted
$table = $wpdb->prefix . 'work_orders';
$data = array(
'contract_id' => $order_id,
'user_id' => $user_id,
'user_name' => $customer_name,
'region' => $region,
'location' => $location,
'min_monthly_hours' => $min_monthly_hours,
'equipement_name' => $equipement_name,
'start_date' => $start_date,
'end_date' => $end_date,
'order_total' => $order_total,
'equip_asset_id' => $equip_asset_id,
'created_date' => current_time('mysql')
);
$inserted = $wpdb->insert($table, $data);
if ($inserted === false) {
$error = $wpdb->last_error;
error_log('Insert work order failed: ' . $error); // Log error
return false;
}
return $wpdb->insert_id;
}