From 75b2f623537fef430845c707a7fc086a50ca7f75 Mon Sep 17 00:00:00 2001
From: Peter Rotich <peter@osticket.com>
Date: Tue, 1 Apr 2014 13:43:26 +0000
Subject: [PATCH] Use templates to show list of tickets or users.

This is necessary so we can use the templates to show tickets assoaciated
with user as well as organization by simply switching the context.
---
 include/staff/org-view.inc.php           |  27 ++--
 include/staff/templates/tickets.tmpl.php | 174 +++++++++++++++++++++++
 include/staff/templates/users.tmpl.php   | 131 +++++++++++++++++
 include/staff/user-view.inc.php          | 150 +------------------
 4 files changed, 317 insertions(+), 165 deletions(-)
 create mode 100644 include/staff/templates/tickets.tmpl.php
 create mode 100644 include/staff/templates/users.tmpl.php

diff --git a/include/staff/org-view.inc.php b/include/staff/org-view.inc.php
index fee2e5181..89a8ee39d 100644
--- a/include/staff/org-view.inc.php
+++ b/include/staff/org-view.inc.php
@@ -51,24 +51,19 @@ if(!defined('OSTSCPINC') || !$thisstaff || !is_object($org)) die('Invalid path')
 <div class="clear"></div>
 <ul class="tabs">
     <li><a class="active" id="users_tab" href="#users"><i
-    class="icon-list-alt"></i>&nbsp;Users</a></li>
+    class="icon-user"></i>&nbsp;Users</a></li>
+    <li><a id="tickets_tab" href="#tickets"><i
+    class="icon-list-alt"></i>&nbsp;Tickets</a></li>
 </ul>
-<div id="users">
-<div style="width:700px; float:left;">
-   <?php
-    if ($results) {
-        echo  sprintf('<strong>Showing 1 - %d of %s</strong>',
-            count($results), count($results));
-    } else {
-        echo 'Organization does not have users';
-    }
-   ?>
-</div>
-<div style="float:right;text-align:right;padding-right:5px;">
-    <b><a class="Icon newStaff" href="users.php?a=open&oid=<?php echo
-    $org->getId(); ?>"> Add New User</a></b>
+<div class="tab_content" id="users">
+<?php
+include STAFFINC_DIR . 'templates/users.tmpl.php';
+?>
 </div>
-<br/>
+<div class="tab_content" id="tickets"  style="display:none;">
+<?php
+include STAFFINC_DIR . 'templates/tickets.tmpl.php';
+?>
 </div>
 
 <script type="text/javascript">
diff --git a/include/staff/templates/tickets.tmpl.php b/include/staff/templates/tickets.tmpl.php
new file mode 100644
index 000000000..bdd562578
--- /dev/null
+++ b/include/staff/templates/tickets.tmpl.php
@@ -0,0 +1,174 @@
+<?php
+
+$select ='SELECT ticket.ticket_id,ticket.`number`,ticket.dept_id,ticket.staff_id,ticket.team_id, ticket.user_id '
+        .' ,dept.dept_name,ticket.status,ticket.source,ticket.isoverdue,ticket.isanswered,ticket.created '
+        .' ,CAST(GREATEST(IFNULL(ticket.lastmessage, 0), IFNULL(ticket.reopened, 0), ticket.created) as datetime) as effective_date '
+        .' ,CONCAT_WS(" ", staff.firstname, staff.lastname) as staff, team.name as team '
+        .' ,IF(staff.staff_id IS NULL,team.name,CONCAT_WS(" ", staff.lastname, staff.firstname)) as assigned '
+        .' ,IF(ptopic.topic_pid IS NULL, topic.topic, CONCAT_WS(" / ", ptopic.topic, topic.topic)) as helptopic '
+        .' ,cdata.priority_id, cdata.subject, user.name, email.address as email';
+
+$from =' FROM '.TICKET_TABLE.' ticket '
+      .' LEFT JOIN '.USER_TABLE.' user ON user.id = ticket.user_id '
+      .' LEFT JOIN '.USER_EMAIL_TABLE.' email ON user.id = email.user_id '
+      .' LEFT JOIN '.USER_ACCOUNT_TABLE.' account ON (ticket.user_id=account.user_id) '
+      .' LEFT JOIN '.DEPT_TABLE.' dept ON ticket.dept_id=dept.dept_id '
+      .' LEFT JOIN '.STAFF_TABLE.' staff ON (ticket.staff_id=staff.staff_id) '
+      .' LEFT JOIN '.TEAM_TABLE.' team ON (ticket.team_id=team.team_id) '
+      .' LEFT JOIN '.TOPIC_TABLE.' topic ON (ticket.topic_id=topic.topic_id) '
+      .' LEFT JOIN '.TOPIC_TABLE.' ptopic ON (ptopic.topic_id=topic.topic_pid) '
+      .' LEFT JOIN '.TABLE_PREFIX.'ticket__cdata cdata ON (cdata.ticket_id = ticket.ticket_id) '
+      .' LEFT JOIN '.PRIORITY_TABLE.' pri ON (pri.priority_id = cdata.priority_id)';
+
+if ($user)
+    $where = 'WHERE ticket.user_id = '.db_input($user->getId());
+elseif ($org)
+    $where = 'WHERE account.org_id = '.db_input($org->getId());
+
+
+TicketForm::ensureDynamicDataView();
+
+$query ="$select $from $where ORDER BY ticket.created DESC";
+
+// Fetch the results
+$results = array();
+$res = db_query($query);
+while ($row = db_fetch_array($res))
+    $results[$row['ticket_id']] = $row;
+
+if ($results) {
+    $counts_sql = 'SELECT ticket.ticket_id,
+        count(DISTINCT attach.attach_id) as attachments,
+        count(DISTINCT thread.id) as thread_count,
+        count(DISTINCT collab.id) as collaborators
+        FROM '.TICKET_TABLE.' ticket
+        LEFT JOIN '.TICKET_ATTACHMENT_TABLE.' attach ON (ticket.ticket_id=attach.ticket_id) '
+     .' LEFT JOIN '.TICKET_THREAD_TABLE.' thread ON ( ticket.ticket_id=thread.ticket_id) '
+     .' LEFT JOIN '.TICKET_COLLABORATOR_TABLE.' collab
+            ON ( ticket.ticket_id=collab.ticket_id) '
+     .' WHERE ticket.ticket_id IN ('.implode(',', db_input(array_keys($results))).')
+        GROUP BY ticket.ticket_id';
+    $ids_res = db_query($counts_sql);
+    while ($row = db_fetch_array($ids_res)) {
+        $results[$row['ticket_id']] += $row;
+    }
+}
+?>
+<div style="width:700px; float:left;">
+   <?php
+    if ($results) {
+        echo  sprintf('<strong>Showing 1 - %d of %s</strong>', count($results), count($results));
+    } else {
+        echo sprintf('%s does not have any tickets', $user? 'User' : 'Organization');
+    }
+   ?>
+</div>
+<div style="float:right;text-align:right;padding-right:5px;">
+    <?php
+    if ($user) { ?>
+    <b><a class="Icon newTicket" href="tickets.php?a=open&uid=<?php echo $user->getId(); ?>"> Create New Ticket</a></b>
+    <?php
+    } ?>
+</div>
+<br/>
+<div>
+<?php
+if ($results) { ?>
+<form action="users.php" method="POST" name='tickets' style="padding-top:10px;">
+<?php csrf_token(); ?>
+ <input type="hidden" name="a" value="mass_process" >
+ <input type="hidden" name="do" id="action" value="" >
+ <table class="list" border="0" cellspacing="1" cellpadding="2" width="940">
+    <thead>
+        <tr>
+            <?php
+            if (0) {?>
+            <th width="8px">&nbsp;</th>
+            <?php
+            } ?>
+            <th width="70">Ticket</th>
+            <th width="100">Date</th>
+            <th width="100">Status</th>
+            <th width="300">Subject</th>
+            <?php
+            if ($user) { ?>
+            <th width="200">Department</th>
+            <th width="200">Assignee</th>
+            <?php
+            } else { ?>
+            <th width="400">User</th>
+            <?php
+            } ?>
+        </tr>
+    </thead>
+    <tbody>
+    <?php
+    foreach($results as $row) {
+        $flag=null;
+        if ($row['lock_id'])
+            $flag='locked';
+        elseif ($row['isoverdue'])
+            $flag='overdue';
+
+        $assigned='';
+        if ($row['staff_id'])
+            $assigned=sprintf('<span class="Icon staffAssigned">%s</span>',Format::truncate($row['staff'],40));
+        elseif ($row['team_id'])
+            $assigned=sprintf('<span class="Icon teamAssigned">%s</span>',Format::truncate($row['team'],40));
+        else
+            $assigned=' ';
+
+        $status = ucfirst($row['status']);
+        if(!strcasecmp($row['status'], 'open'))
+            $status = "<b>$status</b>";
+
+        $tid=$row['number'];
+        $subject = Format::htmlchars(Format::truncate($row['subject'],40));
+        $threadcount=$row['thread_count'];
+        ?>
+        <tr id="<?php echo $row['ticket_id']; ?>">
+            <?php
+            //Implement mass  action....if need be.
+            if (0) { ?>
+            <td align="center" class="nohover">
+                <input class="ckb" type="checkbox" name="tids[]" value="<?php echo $row['ticket_id']; ?>" <?php echo $sel?'checked="checked"':''; ?>>
+            </td>
+            <?php
+            } ?>
+            <td align="center" nowrap>
+              <a class="Icon <?php echo strtolower($row['source']); ?>Ticket ticketPreview" title="Preview Ticket"
+                href="tickets.php?id=<?php echo $row['ticket_id']; ?>"><?php echo $tid; ?></a></td>
+            <td align="center" nowrap><?php echo Format::db_datetime($row['effective_date']); ?></td>
+            <td><?php echo $status; ?></td>
+            <td><a <?php if ($flag) { ?> class="Icon <?php echo $flag; ?>Ticket" title="<?php echo ucfirst($flag); ?> Ticket" <?php } ?>
+                href="tickets.php?id=<?php echo $row['ticket_id']; ?>"><?php echo $subject; ?></a>
+                 <?php
+                    if ($threadcount>1)
+                        echo "<small>($threadcount)</small>&nbsp;".'<i
+                            class="icon-fixed-width icon-comments-alt"></i>&nbsp;';
+                    if ($row['collaborators'])
+                        echo '<i class="icon-fixed-width icon-group faded"></i>&nbsp;';
+                    if ($row['attachments'])
+                        echo '<i class="icon-fixed-width icon-paperclip"></i>&nbsp;';
+                ?>
+            </td>
+            <?php
+            if ($user) { ?>
+            <td><?php echo Format::truncate($row['dept_name'], 40); ?></td>
+            <td>&nbsp;<?php echo $assigned; ?></td>
+            <?php
+            } else { ?>
+            <td>&nbsp;<?php echo sprintf('<a href="users.php?id=%d">%s <em> &lt;%s&gt;</em></a>',
+                    $row['user_id'], $row['name'], $row['email']); ?></td>
+            <?php
+            } ?>
+        </tr>
+   <?php
+    }
+    ?>
+    </tbody>
+</table>
+</form>
+<?php
+ } ?>
+</div>
diff --git a/include/staff/templates/users.tmpl.php b/include/staff/templates/users.tmpl.php
new file mode 100644
index 000000000..6b22d3db9
--- /dev/null
+++ b/include/staff/templates/users.tmpl.php
@@ -0,0 +1,131 @@
+<?php
+
+$qstr='';
+$select = 'SELECT user.*, email.address as email ';
+
+$from = 'FROM '.USER_TABLE.' user '
+      . 'LEFT JOIN '.USER_ACCOUNT_TABLE.' account ON (user.id = account.user_id) '
+      . 'LEFT JOIN '.USER_EMAIL_TABLE.' email ON (user.id = email.user_id) ';
+
+$where='WHERE account.org_id='.db_input($org->getId());
+
+
+$sortOptions = array('name' => 'user.name',
+                     'email' => 'email.address',
+                     'create' => 'user.created',
+                     'update' => 'user.updated');
+$orderWays = array('DESC'=>'DESC','ASC'=>'ASC');
+$sort= ($_REQUEST['sort'] && $sortOptions[strtolower($_REQUEST['sort'])]) ? strtolower($_REQUEST['sort']) : 'name';
+//Sorting options...
+if ($sort && $sortOptions[$sort])
+    $order_column =$sortOptions[$sort];
+
+$order_column = $order_column ?: 'user.name';
+
+if ($_REQUEST['order'] && $orderWays[strtoupper($_REQUEST['order'])])
+    $order = $orderWays[strtoupper($_REQUEST['order'])];
+
+$order=$order ?: 'ASC';
+if ($order_column && strpos($order_column,','))
+    $order_column = str_replace(','," $order,",$order_column);
+
+$x=$sort.'_sort';
+$$x=' class="'.strtolower($order).'" ';
+$order_by="$order_column $order ";
+
+$total=db_count('SELECT count(DISTINCT user.id) '.$from.' '.$where);
+$page=($_GET['p'] && is_numeric($_GET['p']))?$_GET['p']:1;
+$pageNav=new Pagenate($total,$page,PAGE_LIMIT);
+$pageNav->setURL('users.php',$qstr.'&sort='.urlencode($_REQUEST['sort']).'&order='.urlencode($_REQUEST['order']));
+//Ok..lets roll...create the actual query
+$qstr.='&order='.($order=='DESC'?'ASC':'DESC');
+
+$select .= ', count(DISTINCT ticket.ticket_id) as tickets ';
+
+$from .= ' LEFT JOIN '.TICKET_TABLE.' ticket ON (ticket.user_id = user.id) ';
+
+
+$query="$select $from $where GROUP BY user.id ORDER BY $order_by LIMIT ".$pageNav->getStart().",".$pageNav->getLimit();
+//echo $query;
+
+$showing = $search ? 'Search Results: ' : '';
+$res = db_query($query);
+if($res && ($num=db_num_rows($res)))
+    $showing .= $pageNav->showing();
+else
+    $showing .= 'No users found!';
+
+?>
+<div style="width:700px; float:left;"><b><?php echo $showing; ?></b></div>
+<div style="float:right;text-align:right;padding-right:5px;">
+    <b><a href="#orgs/<?php echo $org->getId(); ?>/add-user" class="Icon newstaff add-user">Add New User</a></b></div>
+<div class="clear"></div>
+<br/>
+<form action="users.php" method="POST" name="staff" >
+ <?php csrf_token(); ?>
+ <input type="hidden" name="do" value="mass_process" >
+ <input type="hidden" id="action" name="a" value="" >
+ <table class="list" border="0" cellspacing="1" cellpadding="0" width="940">
+    <thead>
+        <tr>
+            <th width="350"> Name</th>
+            <th width="300"> Email</th>
+            <th width="100"> Status</th>
+            <th width="100"> Created</th>
+        </tr>
+    </thead>
+    <tbody>
+    <?php
+        if($res && db_num_rows($res)):
+            $ids=($errors && is_array($_POST['ids']))?$_POST['ids']:null;
+            while ($row = db_fetch_array($res)) {
+
+                $name = new PersonsName($row['name']);
+                $status = 'Active';
+                $sel=false;
+                if($ids && in_array($row['id'], $ids))
+                    $sel=true;
+                ?>
+               <tr id="<?php echo $row['id']; ?>">
+                <td>&nbsp;
+                    <a href="users.php?id=<?php echo $row['id']; ?>"><?php echo $name; ?></a>
+                    &nbsp;
+                    <?php
+                    if ($row['tickets'])
+                         echo sprintf('<i class="icon-fixed-width icon-file-text-alt"></i>
+                             <small>(%d)</small>', $row['tickets']);
+                    ?>
+                </td>
+                <td><?php echo $row['email']; ?></td>
+                <td><?php echo $status; ?></td>
+                <td><?php echo Format::db_date($row['created']); ?></td>
+               </tr>
+            <?php
+            } //end of while.
+        endif; ?>
+    <tfoot>
+     <tr>
+        <td colspan="4"> &nbsp; </td>
+     </tr>
+    </tfoot>
+</table>
+<?php
+if($res && $num): //Show options..
+    echo '<div>&nbsp;Page:'.$pageNav->getPageLinks().'&nbsp;</div>';
+endif;
+?>
+</form>
+
+<script type="text/javascript">
+$(function() {
+    $(document).on('click', 'a.add-user', function(e) {
+        e.preventDefault();
+        $.userLookup('ajax.php/users/add', function (user) {
+            window.location.href = 'users.php?id='+user.id;
+         });
+
+        return false;
+     });
+});
+</script>
+
diff --git a/include/staff/user-view.inc.php b/include/staff/user-view.inc.php
index a73199124..5ad4478c7 100644
--- a/include/staff/user-view.inc.php
+++ b/include/staff/user-view.inc.php
@@ -124,156 +124,8 @@ $org = $account ? $account->getOrganization() : null;
 </ul>
 <div id="tickets">
 <?php
-//List all tickets the user
-
-$select ='SELECT ticket.ticket_id,ticket.`number`,ticket.dept_id,ticket.staff_id,ticket.team_id '
-        .' ,dept.dept_name,ticket.status,ticket.source,ticket.isoverdue,ticket.isanswered,ticket.created '
-        .' ,CAST(GREATEST(IFNULL(ticket.lastmessage, 0), IFNULL(ticket.reopened, 0), ticket.created) as datetime) as effective_date '
-        .' ,CONCAT_WS(" ", staff.firstname, staff.lastname) as staff, team.name as team '
-        .' ,IF(staff.staff_id IS NULL,team.name,CONCAT_WS(" ", staff.lastname, staff.firstname)) as assigned '
-        .' ,IF(ptopic.topic_pid IS NULL, topic.topic, CONCAT_WS(" / ", ptopic.topic, topic.topic)) as helptopic '
-        .' ,cdata.priority_id, cdata.subject, pri.priority_desc, pri.priority_color';
-
-$from =' FROM '.TICKET_TABLE.' ticket '
-      .' LEFT JOIN '.DEPT_TABLE.' dept ON ticket.dept_id=dept.dept_id '
-      .' LEFT JOIN '.STAFF_TABLE.' staff ON (ticket.staff_id=staff.staff_id) '
-      .' LEFT JOIN '.TEAM_TABLE.' team ON (ticket.team_id=team.team_id) '
-      .' LEFT JOIN '.TOPIC_TABLE.' topic ON (ticket.topic_id=topic.topic_id) '
-      .' LEFT JOIN '.TOPIC_TABLE.' ptopic ON (ptopic.topic_id=topic.topic_pid) '
-      .' LEFT JOIN '.TABLE_PREFIX.'ticket__cdata cdata ON (cdata.ticket_id = ticket.ticket_id) '
-      .' LEFT JOIN '.PRIORITY_TABLE.' pri ON (pri.priority_id = cdata.priority_id)';
-
-$where = 'WHERE ticket.user_id = '.db_input($user->getId());
-
-TicketForm::ensureDynamicDataView();
-
-$query ="$select $from $where ORDER BY ticket.created DESC";
-
-// Fetch the results
-$results = array();
-$res = db_query($query);
-while ($row = db_fetch_array($res))
-    $results[$row['ticket_id']] = $row;
-
-if ($results) {
-    $counts_sql = 'SELECT ticket.ticket_id,
-        count(DISTINCT attach.attach_id) as attachments,
-        count(DISTINCT thread.id) as thread_count,
-        count(DISTINCT collab.id) as collaborators
-        FROM '.TICKET_TABLE.' ticket
-        LEFT JOIN '.TICKET_ATTACHMENT_TABLE.' attach ON (ticket.ticket_id=attach.ticket_id) '
-     .' LEFT JOIN '.TICKET_THREAD_TABLE.' thread ON ( ticket.ticket_id=thread.ticket_id) '
-     .' LEFT JOIN '.TICKET_COLLABORATOR_TABLE.' collab
-            ON ( ticket.ticket_id=collab.ticket_id) '
-     .' WHERE ticket.ticket_id IN ('.implode(',', db_input(array_keys($results))).')
-        GROUP BY ticket.ticket_id';
-    $ids_res = db_query($counts_sql);
-    while ($row = db_fetch_array($ids_res)) {
-        $results[$row['ticket_id']] += $row;
-    }
-}
+include STAFFINC_DIR . 'templates/tickets.tmpl.php';
 ?>
-<div style="width:700px; float:left;">
-   <?php
-    if ($results) {
-        echo  sprintf('<strong>Showing 1 - %d of %s</strong>',
-            count($results), count($results));
-    } else {
-        echo sprintf('%s does not have any tickets', $user->getName());
-    }
-   ?>
-</div>
-<div style="float:right;text-align:right;padding-right:5px;">
-    <b><a class="Icon newTicket" href="tickets.php?a=open&uid=<?php echo $user->getId(); ?>"> Create New Ticket</a></b>
-</div>
-<br/>
-<?php
-if ($results) { ?>
-<form action="users.php" method="POST" name='tickets' style="padding-top:10px;">
-<?php csrf_token(); ?>
- <input type="hidden" name="a" value="mass_process" >
- <input type="hidden" name="do" id="action" value="" >
- <table class="list" border="0" cellspacing="1" cellpadding="2" width="940">
-    <thead>
-        <tr>
-            <?php
-            if (0) {?>
-            <th width="8px">&nbsp;</th>
-            <?php
-            } ?>
-            <th width="70">Ticket</th>
-            <th width="100">Date</th>
-            <th width="100">Status</th>
-            <th width="250">Subject</th>
-            <th width="100">Priority</th>
-            <th width="250">Department</th>
-            <th width="200">Assignee</th>
-        </tr>
-    </thead>
-    <tbody>
-    <?php
-    foreach($results as $row) {
-        $flag=null;
-        if ($row['lock_id'])
-            $flag='locked';
-        elseif ($row['isoverdue'])
-            $flag='overdue';
-
-        $assigned='';
-        if ($row['staff_id'])
-            $assigned=sprintf('<span class="Icon staffAssigned">%s</span>',Format::truncate($row['staff'],40));
-        elseif ($row['team_id'])
-            $assigned=sprintf('<span class="Icon teamAssigned">%s</span>',Format::truncate($row['team'],40));
-        else
-            $assigned=' ';
-
-        $status = ucfirst($row['status']);
-        if(!strcasecmp($row['status'], 'open'))
-            $status = "<b>$status</b>";
-
-        $tid=$row['number'];
-        $subject = Format::htmlchars(Format::truncate($row['subject'],40));
-        $threadcount=$row['thread_count'];
-        ?>
-        <tr id="<?php echo $row['ticket_id']; ?>">
-            <?php
-            //Implement mass  action....if need be.
-            if (0) { ?>
-            <td align="center" class="nohover">
-                <input class="ckb" type="checkbox" name="tids[]" value="<?php echo $row['ticket_id']; ?>" <?php echo $sel?'checked="checked"':''; ?>>
-            </td>
-            <?php
-            } ?>
-            <td align="center" nowrap>
-              <a class="Icon <?php echo strtolower($row['source']); ?>Ticket ticketPreview" title="Preview Ticket"
-                href="tickets.php?id=<?php echo $row['ticket_id']; ?>"><?php echo $tid; ?></a></td>
-            <td align="center" nowrap><?php echo Format::db_datetime($row['effective_date']); ?></td>
-            <td><?php echo $status; ?></td>
-            <td><a <?php if ($flag) { ?> class="Icon <?php echo $flag; ?>Ticket" title="<?php echo ucfirst($flag); ?> Ticket" <?php } ?>
-                href="tickets.php?id=<?php echo $row['ticket_id']; ?>"><?php echo $subject; ?></a>
-                 <?php
-                    if ($threadcount>1)
-                        echo "<small>($threadcount)</small>&nbsp;".'<i
-                            class="icon-fixed-width icon-comments-alt"></i>&nbsp;';
-                    if ($row['collaborators'])
-                        echo '<i class="icon-fixed-width icon-group faded"></i>&nbsp;';
-                    if ($row['attachments'])
-                        echo '<i class="icon-fixed-width icon-paperclip"></i>&nbsp;';
-                ?>
-            </td>
-            <td class="nohover" align="center" style="background-color:<?php echo $row['priority_color']; ?>;">
-                <?php echo $row['priority_desc']; ?></td>
-            <td><?php echo Format::truncate($row['dept_name'], 40); ?></td>
-            <td>&nbsp;<?php echo $assigned; ?></td>
-        </tr>
-   <?php
-    }
-    ?>
-    </tbody>
-</table>
-</form>
-<?php
- } ?>
 </div>
 
 <div style="display:none;" class="dialog" id="confirm-action">
-- 
GitLab