CommonwellBrokerListManager.php 25.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
<?php
/**
 * Plugin Name: Underwriting Team Manager
 * Version: 1.0
 * Author: Tenzing Communications, Inc.
 * Description: Manage a broker list from Commonwell active directory.
 */

if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

class CommonwellBrokerListManager extends WP_List_Table
{
    /** Class constructor */
    public function __construct()
    {
        parent::__construct(
            [
                'singular' => __('Broker', 'tz'), //singular name of the listed records
                'plural'   => __('Brokers', 'tz'), //plural name of the listed records
                'ajax'     => false //does this table support ajax?
            ]
        );
    }

    /**
     * Retrieve broker data from the database
     *
     * @param int $per_page
     * @param int $page_number
     *
     * @return mixed
     */
    public static function get_broker_list($per_page = 5, $page_number = 1)
    {
        global $wpdb;
        $sql = "SELECT * FROM {$wpdb->prefix}broker_list";
        if (!empty($_REQUEST['orderby'])) {
            $sql .= ' ORDER BY ' . esc_sql($_REQUEST['orderby']);
            $sql .= !empty($_REQUEST['order']) ? ' ' . esc_sql($_REQUEST['order']) : ' ASC';
        }
        $sql    .= " LIMIT $per_page";
        $sql    .= ' OFFSET ' . ($page_number - 1) * $per_page;
        $result = $wpdb->get_results($sql, 'ARRAY_A');

        return $result;
    }


    /**
     * Delete a customer record.
     *
     * @param int $id customer ID
     */
    public static function delete_broker($id)
    {
        global $wpdb;
        $wpdb->delete(
            "{$wpdb->prefix}broker_list",
            ['ID' => $id],
            ['%d']
        );
    }

    /**
     * Returns the count of records in the database.
     *
     * @return null|string
     */
    public static function record_count()
    {
        global $wpdb;
        $sql = "SELECT COUNT(*) FROM {$wpdb->prefix}broker_list";

        return $wpdb->get_var($sql);
    }

    /** Text displayed when no customer data is available */
    public function no_items()
    {
        _e('No broker found.', 'tz');
    }

    /**
     * Render a column when no column specific method exist.
     *
     * @param array  $item
     * @param string $column_name
     *
     * @return mixed
     */
    public function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'id':
            case 'broker_org_name':
            case 'broker_id':
            case 'group_name_in_ad':
            case 'group_id':
                return $item[$column_name];
            default:
                return print_r($item, true);
        }
    }

    /**
     * Render the bulk edit checkbox
     *
     * @param array $item
     *
     * @return string
     */
    function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="bulk-delete[]" value="%s" />',
            $item['id']
        );
    }

    /**
     * Method for name column
     *
     * @param array $item an array of DB data
     *
     * @return string
     */
    function column_broker_org_name($item)
    {
        $delete_nonce = wp_create_nonce('tz_delete_broker');
        $edit_nonce   = wp_create_nonce('tz_edit_broker');
		

        $title   = '<strong>' . $item['broker_org_name'] . '</strong>';
        $actions = [
            'delete' => sprintf(
                '<a href="?page=%s&action=%s&broker=%s&_wpnonce=%s">Delete</a>',
                esc_attr($_REQUEST['page']),
                'delete',
                absint($item['id']),
                $delete_nonce
            ),
            'edit'   => sprintf(
                '<a href="?page=%s&action=%s&broker=%s&_wpnonce=%s">Edit</a>',
                esc_attr($_REQUEST['page']),
                'edit',
                absint($item['id']),
                $edit_nonce
            ),

        ];

        return $title . $this->row_actions($actions);
    }

    /**
     *  Associative array of columns
     *
     * @return array
     */
    function get_columns()
    {
        $columns = [
            'cb'               => '<input type="checkbox" />',
            'broker_org_name'  => __('Broker Org Name', 'tz'),
            'broker_id'        => __('Broker ID', 'tz'),
            'group_name_in_ad' => __('Group Name in AD', 'tz')
        ];

        return $columns;
    }

    /**
     * Columns to make sortable.
     *
     * @return array
     */
    public function get_sortable_columns()
    {
        $sortable_columns = array(
            'broker_org_name'  => array('broker_org_name', true),
            'broker_id'        => array('broker_id', false),
            'group_name_in_ad' => array('group_name_in_ad', false)
        );

        return $sortable_columns;
    }

    /**
     * Returns an associative array containing the bulk action
     *
     * @return array
     */
    public function get_bulk_actions()
    {
        $actions = [
            'bulk-delete' => 'Delete'
        ];

        return $actions;
    }

    public function column_group_name_in_ad($item)
    {
        return $item['group_name_in_ad'] . ' : ' . $item['group_id'];
    }

    /**
     * Handles data query and filter, sorting, and pagination.
     */
    public function prepare_items()
    {
        $this->_column_headers = $this->get_column_info();
        /** Process bulk action */
        $this->process_bulk_action();
        $per_page     = $this->get_items_per_page('broker_list_per_page', 5);
        $current_page = $this->get_pagenum();
        $total_items  = self::record_count();
        $this->set_pagination_args(
            [
                'total_items' => $total_items, //WE have to calculate the total number of items
                'per_page'    => $per_page //WE have to determine how many items to show on a page
            ]
        );
        $this->items = self::get_broker_list($per_page, $current_page);
    }

    public function process_bulk_action()
    {
        //Detect when a bulk action is being triggered...
        if ('delete' === $this->current_action()) {
            // In our file that handles the request, verify the nonce.
            $nonce = esc_attr($_REQUEST['_wpnonce']);
            if (!wp_verify_nonce($nonce, 'tz_delete_broker')) {
                die('Go get a life script kiddies');
            } else {
                self::delete_broker(absint($_GET['broker']));
                // esc_url_raw() is used to prevent converting ampersand in url to "#038;"
                // add_query_arg() return the current url
                wp_redirect(esc_url_raw(remove_query_arg('action')));
                //                exit;
            }
        }
        // If the delete bulk action is triggered
        if ((isset($_POST['action']) && $_POST['action'] == 'bulk-delete')
            || (isset($_POST['action2']) && $_POST['action2'] == 'bulk-delete')
        ) {
            $delete_ids = esc_sql($_POST['bulk-delete']);
            // loop over the array of record IDs and delete them
            foreach ($delete_ids as $id) {
                self::delete_broker($id);
            }
            // esc_url_raw() is used to prevent converting ampersand in url to "#038;"
            // add_query_arg() return the current url
            wp_redirect(esc_url_raw(add_query_arg()));
            //            exit;
        }
    }

    /**
     * Generate the table rows
     *
     * @since 3.1.0
     * @access public
     */
    public function display_rows()
    {
        if (isset($_POST['s']) && $_POST['s'] != '') {
            foreach ($this->items as $item) {
                if (preg_grep('/' . $_POST['s'] . '/i', $item)) {
                    $this->single_row($item);
                } else {
                    continue;
                }
            }
        } else {
            foreach ($this->items as $item) {
                $this->single_row($item);
            }
        }
    }

    /**
     * Display the search box.
     *
     * @since 3.1.0
     * @access public
     *
     * @param string $text The search button text
     * @param string $input_id The search input id
     */
    public function search_box($text, $input_id)
    {
        if (empty($_REQUEST['s']) && !$this->has_items()) {
            return;
        }

        $input_id = $input_id . '-search-input';

        if (!empty($_REQUEST['orderby'])) {
            echo '<input type="hidden" name="orderby" value="' . esc_attr($_REQUEST['orderby']) . '" />';
        }
        if (!empty($_REQUEST['order'])) {
            echo '<input type="hidden" name="order" value="' . esc_attr($_REQUEST['order']) . '" />';
        }
        if (!empty($_REQUEST['post_mime_type'])) {
            echo '<input type="hidden" name="post_mime_type" value="' . esc_attr($_REQUEST['post_mime_type']) . '" />';
        }
        if (!empty($_REQUEST['detached'])) {
            echo '<input type="hidden" name="detached" value="' . esc_attr($_REQUEST['detached']) . '" />';
        }
        ?>
        <p class="search-box">
            <label class="screen-reader-text" for="<?php echo $input_id ?>"><?php echo $text; ?>:</label>
            <input type="search" id="<?php echo $input_id ?>" name="s" value="<?php _admin_search_query(); ?>" />
            <?php submit_button($text, 'button', false, false, array('id' => 'search-submit')); ?>
        </p>
        <?php
    }

}

class TZ_Plugin
{
    // class instance
    static $instance;
    // customer WP_List_Table object
    public $brokerListManagerObj;

    // class constructor
    public function __construct()
    {
        add_filter('set-screen-option', [__CLASS__, 'set_screen'], 10, 3);
        add_action('admin_menu', [$this, 'plugin_menu']);
    }

    public static function set_screen($status, $option, $value)
    {
        return $value;
    }

    public function plugin_menu()
    {
        $hook = add_menu_page(
            'Underwriting Teams',
            'Underwriting Teams',
            'manage_options',
            'commonwell_broker_list_manager',
            [$this, 'plugin_settings_page']
        );
        add_action("load-$hook", [$this, 'screen_option']);

        // Add sub pages
        add_submenu_page(
            'commonwell_broker_list_manager',
            'Assign New Underwriting Team',
            'Assign Underwriting Team',
            'manage_options',
            'add_new_broker',
            array($this, 'add_new_broker_page')
        );
    }

    public function add_new_broker_page()
    {
        global $wpdb;
        $isSuccess = false;

        // Is submitted?
        if (isset($_POST['submit'])) {
            // Update Broker Info
			$brokerList = get_option('broker_list') ? unserialize(get_option('broker_list')) : [];
			$key = array_search($_POST['broker_id'], array_column($brokerList, 'broker_id'));
            $result = $wpdb->insert(
                "{$wpdb->prefix}broker_list",
                [
                    'broker_id' => $_POST['broker_id'],
                    'broker_org_name' => $brokerList[$key]['brokerage'],
                    'group_name_in_ad' => $_POST['group_name_in_ad'],
                    'group_id' => $_POST['group_id']
                ]
            );

            if($result) {
                $isSuccess = true;
            }
			
        print('<script>window.location.href="admin.php?page=commonwell_broker_list_manager"</script>');
 		exit;
        }

        // Get group from Commonwell AD
        $groups = GraphServiceAccessHelper::getFeed('groups');
        $groupIds = $wpdb->get_col("SELECT group_id FROM {$wpdb->prefix}broker_list");
		        
        $brokerList = get_option('broker_list') ? unserialize(get_option('broker_list')) : [];

        // Check if the group objectId exists.
        $groupList = array_filter($groups, function($group) use($groupIds) {
            $inArray = in_array($group->objectId, $groupIds);
            return !$inArray;
        });

        ?>
        <style>
            #poststuff form input[type="text"] {
                width : 100%;
            }
        </style>
        <div class="wrap">
            <h2>Underwriting Team Manager</h2>
            <div id="poststuff">
                <div id="post-body" class="metabox-holder columns-2">
                    <div id="post-body-content">
                        <div class="meta-box-sortables ui-sortable">
                            <h3>Assign Underwriting Team</h3>
                            <?php if (isset($_POST['submit']) && $isSuccess) : ?>
                                <div id="message" class="updated notice notice-success is-dismissible">
                                    <p>Assigned Underwriting Team</p>
                                    <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span>
                                    </button>
                                </div>
                            <?php endif; ?>
                            <form method="post" id="new-broker-form">
                                <table class="wp-list-table widefat fixed striped">
                                    <tbody>
                              
                                     <tr>
                                      <td>
                                            <label for="broker_id">Broker ID: </label>
                                        </td>
                                        <td>
                                      
                                        <select name="broker_id" id="broker_id" required>
                                                <option value=""> -- Broker -- </option>
                                                <?php
                                                foreach ($brokerList as $broker) { ?>
                                                
                                                    <option value="<?php echo $broker['broker_id'] ?>" data-group-id="<?php echo $broker['broker_id'];?>"> <?php echo $broker['brokerage']; ?></option>
                                                <?php } ?>
                                            </select>
                                                </td>
                                    <tr>
                                        <td>
                                            <label for="group_name_in_ad">Group Name in AD: </label>
                                        </td>
                                        <td>
                                            <select name="group_name_in_ad" id="group_name_in_ad" required>
                                                <option value=""> -- Group Name -- </option>
                                                <?php
                                                foreach ($groupList as $group) { ?>
                                                    <option value="<?php echo trim($group->displayName); ?>" data-group-id="<?php echo trim($group->objectId);?>"> <?php echo $group->displayName; ?></option>
                                                <?php } ?>
                                            </select>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                                <input type="hidden" name="group_id" id="group_id" value=""/>

                                <br class="clear">
                                <input type="submit" name="submit" id="submit"
                                       class="button button-primary button-large" value="Submit">
                            </form>
                            <script>
                                (function($) {
                                    var $newBrokerForm = $('#new-broker-form');
                                    var $groupDropdown = $newBrokerForm.find('#group_name_in_ad');
                                    var $groupId = $('#group_id');

                                    $groupDropdown.on('change', setGroupId).trigger('change');

                                    function setGroupId(e) {
                                        var objectId = e.target.selectedOptions[0].dataset.groupId;
                                        $groupId.val(objectId);
                                    }
                                })(jQuery);
                            </script>
                        </div>
                    </div>
                </div>
                <br class="clear">
            </div>
        </div>
        <?php
    }

    /**
     * Plugin settings page
     */
    public function plugin_settings_page()
    {
        // Broker edit action
        ?>
        <?php if (isset($_GET['action']) && $_GET['action'] === 'edit') : ?>
        <?php
        global $wpdb;

        $isSuccess     = false;
        $id            = isset($_GET['broker']) ?  $_GET['broker'] : '';

        // Is submitted?
        if (isset($_POST['submit'])) {
            // Update Broker Info
			$brokerList = get_option('broker_list') ? unserialize(get_option('broker_list')) : [];
			$key = array_search($_POST['broker_id'], array_column($brokerList, 'broker_id'));
			
            $result = $wpdb->update(
                "{$wpdb->prefix}broker_list",
                [
                    'broker_id' => $_POST['broker_id'],
                    'broker_org_name' => $brokerList[$key]['brokerage'],
                    'group_name_in_ad' => $_POST['group_name_in_ad'],
                    'group_id' => $_POST['group_id']

                ],
                ['id' => $id]
            );

            if($result) {
                $isSuccess = true;
				
        

			}
		print('<script>window.location.href="admin.php?page=commonwell_broker_list_manager"</script>');
 		exit;
				
				
          
        }

        $currentBroker = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}broker_list WHERE id={$id}", ARRAY_A)[0];
        $currentBrokerGroupName = $currentBroker['group_name_in_ad'];
        $currentBrokerGroupId = $currentBroker['group_id'];
		$currentBrokerId = $currentBroker['broker_id'];
	

        // Get group from Commonwell AD
        $groups = GraphServiceAccessHelper::getFeed('groups');
        $groupIds = $wpdb->get_col("SELECT group_id FROM {$wpdb->prefix}broker_list");

        // Check if the group objectId exists.
        $groupList = array_filter($groups, function($group) use($groupIds, $currentBrokerGroupId) {
            $inArray = in_array($group->objectId, $groupIds);
            return !$inArray || ($group->objectId === $currentBrokerGroupId);
        });
		// Get group from Commonwell AD
       
        
        $brokerList = get_option('broker_list') ? unserialize(get_option('broker_list')) : [];
       
	
        ?>
        <style>
            #poststuff form input[type="text"] {
                width : 100%;
            }
        </style>
        <div class="wrap">
            <h2>Underwriting Team Manager</h2>
            <div id="poststuff">
                <div id="post-body" class="metabox-holder columns-2">
                    <div id="post-body-content">
                        <div class="meta-box-sortables ui-sortable">
                            <h3>Edit Assigned Underwriting Team</h3>
                            <?php if (isset($_POST['submit']) && $isSuccess) : ?>
                                <div id="message" class="updated notice notice-success is-dismissible">
                                    <p>Assigned Underwriting Team edited.</p>
                                    <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span>
                                    </button>
                                </div>
                            <?php endif; ?>
                            <form method="post" id="edit-broker-form" action="">
                                <table class="wp-list-table widefat fixed striped">
                                    <tbody>
                       
                                        <td>
                                            <label for="broker_id">Broker ID: </label>
                                        </td>
                                        <td>
                                      
                                        <select name="broker_id" id="broker_id" required>
                                                <option value=""> -- Broker -- </option>
                                                <?php
                                                foreach ($brokerList as $broker) { ?>
                                                    <?php
													
       
                                                    $isSelected = $broker['broker_id'] === $currentBrokerId ? 'selected' : '';
                                                    ?>
                                                    <option <?php echo $isSelected; ?> value="<?php echo $broker['broker_id'] ?>" data-group-id="<?php echo $broker['broker_id'];?>"> <?php echo $broker['brokerage']; ?></option>
                                                <?php } ?>
                                            </select>
                                                </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <label for="group_name_in_ad">Group Name in AD: </label>
                                        </td>
                                        <td>
                                            <select name="group_name_in_ad" id="group_name_in_ad" required>
                                                <option value=""> -- Group Name -- </option>
                                                <?php
                                                foreach ($groupList as $group) { ?>
                                                    <?php
                                                    $isSelected = $group->displayName === $currentBrokerGroupName ? 'selected' : '';
                                                    ?>
                                                    <option <?php echo $isSelected; ?> value="<?php echo $group->displayName ?>" data-group-id="<?php echo $group->objectId;?>"> <?php echo $group->displayName; ?></option>
                                                <?php } ?>
                                            </select>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                                <input type="hidden" name="group_id" id="group_id" value=""/>

                                <br class="clear">
                                <input type="submit" name="submit" id="submit"
                                       class="button button-primary button-large" value="Submit">
                            </form>

                            <script>
                                (function($) {
                                    var $editBrokerForm = $('#edit-broker-form');
                                    var $groupDropdown = $editBrokerForm.find('#group_name_in_ad');
                                    var $groupId = $('#group_id');

                                    $groupDropdown.on('change', setGroupId).trigger('change');

                                    function setGroupId(e) {
                                        var objectId = e.target.selectedOptions[0].dataset.groupId;
                                        $groupId.val(objectId);
                                    }
                                })(jQuery);
                            </script>
                        </div>
                    </div>
                </div>
                <br class="clear">
            </div>
        </div>
    <?php else : ?>
        <div class="wrap">
            <h2>Underwriting Team Manager</h2>
            <div id="poststuff">
                <div id="post-body" class="metabox-holder columns-2">
                    <div id="post-body-content">
                        <div class="meta-box-sortables ui-sortable">
                            <h3 style="margin-bottom: 0;">Underwriting Teams<a href="/wp-admin/admin.php?page=add_new_broker"
                                                                     class="page-title-action">Assign Underwriting Team</a></h3>
                            <form method="post">
                                <?php
                                $this->brokerListManagerObj->prepare_items();
                                $this->brokerListManagerObj->search_box('search', 'search_id');
                                $this->brokerListManagerObj->display(); ?>
                            </form>
                        </div>
                    </div>
                </div>
                <br class="clear">
            </div>
        </div>
    <?php endif; ?>
        <?php
    }

    /**
     * Screen options
     */
    public function screen_option()
    {
        $option = 'per_page';
        $args   = [
            'label'   => 'Broker List Manager',
            'default' => 5,
            'option'  => 'broker_list_per_page'
        ];
        add_screen_option($option, $args);
        $this->brokerListManagerObj = new CommonwellBrokerListManager();
    }

    /** Singleton instance */
    public static function get_instance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}

add_action(
    'plugins_loaded',
    function () {
        TZ_Plugin::get_instance();
    }
);