Monday, November 27, 2017

An AngularJS Dashboard, Part 8: Mobile Improvements and Role Support

NOTE: for best results, view the http: version of this page (else you won't get syntax highlighting).

This is Part 8 in a series on creating a dashboard in AngularJS. I'm blogging as I progressively create the dashboard, refining my Angular experience along the way. An online demo of the latest work is available here.

Previously in Part 7, we added a smart tile fill algorithm, improving how our dashboard renders regardless of the layout's mix of tile sizes or the width of the browser window. Today in Part 8, we're going to focus on two areas: improving the mobile experience abd adding role support. We'll be improving the mobile experience by setting a better initial viewport page width on devices and implementing a friendler way to re-arrange the dashboard. By role support, we mean restricting who can see certain dashboard information and adding the ability to customize dashboards for different roles/departments.

Today we will:
• Add a meta tag for viewport sizing on mobile devices
• Detect a too-small mobile width and adjust viewport size
• Add an alternative to drag-and-drop for reordering tiles on mobile devices
• Relocate some actions in the tile action menu into a second dashboard menu
• Add a new tile action, Copy Tile
• Allow different users to sign in to our demo project
• Track roles for users
• Support dashboards layouts for roles
• Allow tiles to be restricted to a role
• Add personalized tiles through the use of data queries that filter data for the current user

Here's a glimpse of what we'll end up with today:

Today's objective

A Better Mobile Experience

While we haven't exactly ignored mobile devices up till now, we haven't really focused on making mobile a fantastic experience. If you look back at earlier posts in the series, you'll see that the mobile views werewelltoo big. Although the tile layout would re-render for available space, the size of the dashboard layout was simply too large, which meant the tile content and menus were too small to be of practical use to a mobile user.

MOBILE VIEWPORT

By default, mobile device browsers fully expect to be handed pages that are too large for their screen size; as a practical matter, they therefore support zooming and scrolling. Because our markup hasn't addressed this behavior, our dashboard has been rendering too packed on small screens, resulting in text that is too small to read and controls that are too small to interact with. Although the user could certainly scale the page, they shouldn't have to. What we want is a great out-of-the-box display on phones and tables that is easy to interact with.

Fortunately, there is an element we can add to our markup that addresses this: a meta tag that sets viewport size. The typical tag looks like this, which is also what we'll use:

<meta id="viewport" name="viewport" content="width=device-width, initial-scale=1"> 

This immediately makes things better, but doesn't solve all of our problems. The smallest possible rendering of our dashboard is one tile across, but since tiles can be 1- or 2-units wide/tall, we can't really render dashboards well unless we're sure we have enough room for 2 tile units across-or 16 + 200 + 16 + 200 + 16. On something like a portrait iPhone we might be only 375 pixels wide. We're going need to add logic, then, to check whether our screen width is under 500 pixels. If it is, we're going to use jQuery to replace our meta viewport tag with a different one, telling the device to scale to 500 pixels across. This will give us room to render our dashboard.
var scope1, ctrl1;
$(document).ready(function () {
    if (window.innerWidth < 500) {  // If device is so small we can't fit a wide tile, scale meta viewport tag to minimum width of 500px
        var mvp = document.getElementById('viewport');
        mvp.setAttribute('content', 'width=500');
    }
    if (typeof google != 'undefined') {
        google.charts.load("current", { packages: ["corechart", 'table'] });
    }
});

With this in place, we can now try our dashboard out on a variety of mobile devices. When we do, as the results below show, we are seeing markedly improved displays that are large enough to read and use. The desktop, which previously looked fine, remains unchanged.

Dashboard on Android Phone (Portrait)

Dashboard on iPad (Landscape)

Dashboard on Desktop

Tile Menu and Dashboard Menu

Up until now, our tiles have had a tile menu. An ellipsis appears at the top right of a tile, when hovered over or clicked on, revealing a menu of tile and dashboard actions. Some of those actions really affect the entire dashboard, not just the current tile: Add Tile, Reset Dashboard, Make Default Layout. To factor things better in the UI, we now have a separate dashboard menu for dashboard actions, represented by a gear icon at top right.

Dashboard Menu

The tile menu remains, with a smaller number of options. We've also added a new tile action, Copy Tile, which adds a copy of the current tile to the layout.

Tile Menu

Rearranging Tiles

A second mobile concern is the way we've provided users to rearrange tile layout: drag-and-drop. This works great from the desktop, but is problematic on Android and iOS mobile devices. Although we've previously added the Touch-Punch JavaScript library to get touch events working, the experience is still problematic--especially on iOS devices. We also experimented with adding some polyfills for HTML5 drag and drop, but none of this solved the issue. What we've decided to do, then, is replace drag-and-drop on mobile devices with a reordering dialog.

The Rearrange Tiles action now displays the following dialog on devices 1024 wide or smaller:

Mobile Reorder Tiles Dialog

The user can quickly move tiles up or down by touching the arrow keys. As the tile order is changed, the dashboard layout updates live. Clicking Save commits changes, and Cancel undoes them.

On the desktop, Rearrange Tiles continues to provide the same drag-and-drop experience we've had previously. Now every user can customize their dashboard layout easily, regardless of the device they're using.

Role Support

Dashboards are all about providing meaningful information at-a-glance--but that information isn't necesarily meant for all eyes. To make ng-dashboard smarter about what it shows, we need awareness of a user's roles.

User Logins

In order to make it easy to test out how roles are working, our simple test project has been upgraded. The current user is displayed at top right, and by clicking on the name you can select a different login from the drop-down menu. You can choose between John Smith (an Admin), Marcia Brady (a Manager), and Stuart Downey (in Sales). The code will set a cookie and remember who you are; and if you're signing on for the first time, it will log you in as john.smith. There are no passwords to worry about.

Changing login

Representing Roles

Since our dashboard as we release it is just in a simple test project without real security, how do will we handle role management? We're going to assume that whatever authentication/authorization system you have, each user can be said to be in one or more roles/departments--and that those roles can be represented by an array of string names, such as "Employee", "Manager", "Executive", "Sales", "Accounting", etc. In addition, we are attaching special significance to the role "Admin": this role gets access to advanced dashboard actions such as Make Default Layout. This scheme should hopefully be easily adaptible to your authN/authZ system.

In our test project's MVC controller, a few user names are hard-coded (john.smith, an Admin; marcia.brady, a manager; and Stuart Downey, a salesman). This would more properly be driven by our database, but that work is still on the backlog.

Role Defaults for Dashboards 

Up until now, we have had two places to look for the user's dashboard when we load it. First, if the user has saved a custom edition of their dashboard this will be in the DashboardLayout table under the user's username. If that isn't found, the code will look for the default dashboard for all users, stores in the same table under username 'default'. This was done with a query order by Priority that selected the top 1 match. This ensured a customized layout would be selected if one existed for the user, otherwise the default layout would be used.

All of that is working well, but it would be valuable to also store default layouts for various roles.
Imagine for example that you've set up the perfect dashboard for salespeople in your organization--how do you get it to all your salespeople, and to new salespeople who join the company in the future? Using the 'default' layout ins't a good idea, because not everyone in your organization is a salesperson; and a customized layout for one user is only available to that one user. What we need, then, is another level where a dashboard layout can be saved for a role. With today's update, the code now searches for a dashboard to show the user in a 3-level search:

1. User Saved Custom Layout: Use the saved custom dashboard with username=.
2. Default Role Layout: Otherwise, use the saved custom dashboard with username=.
3. Default Layout: Otherwise, use the default dashboard for all users (username='default').

Step 2 needs some explanation, because a user can be in multiple roles; if a user was in both the Manger and Sales roles, and dashboards were defined for each role, which one should be used? The way we handle that is to use the Priority field already built in to the DashboardLayout table. The default layout is priority 1, and saved user custom layouts are priority 10. That leaves priorities 2-8 for role-based layouts. If ng-dashboard found a Sales dashboard with priority 3 and a Manager dashboard with priority 5, it would choose the Sales dashboard. This is the query used to select a matching dashboard based on priority:

SELECT TOP 1 DashboardId FROM DashboardLayout 
WHERE DashboardName='Home' AND
Username=username OR Username IN (role-list) OR Username='default')
ORDER BY [Priority] DESC

Although the addition of role support is important and useful, note that we do not yet have UI support for it--another item for our backlog. That means, right now, you'd need to do some databasee work in order to define a role-based layout in the database in order to use it. Probably the easiest way to do that right now is to first save a custom layout, then update the DashboardLayout record's priority and username (to be a role name).

With all of this in place, we now have a default dashboard layout for everybody, the ability to specify default layouts for different roles, all while preserving a user's right to customize their dashboard layout to their liking.

Restricting Tiles to a Role

It would be useful to be able to restrict some dashboard information to certain roles. For example, you might want to limit compensation information to Accounting, or perhaps limit order information to Sales, or restrict employee information to their manager. Although you could take the approach of designing different dashboard for different departments or roles, that doesn't work well in practice; it's more useful to be able to restrict things at the tile level, so that good dashboard layouts can be freely across the organization without fear of someone seeing something they shouldn't.

Our approach will be to two-fold. First , we've added a role column to the database DashboardQuery table. This allows us to indicate that a query requires a role, such as Manager. When the MVC controller loads queries to pass on to the Angular controller, it will not include any queries the user isn't authorized for.

Secondly, we've added a role property to tiles.  Here's the tile configuration dialog with the new Required Role input. If a role is specified, the tile will only be available to users in that role; if a user without the required role accesses the dashboard, the tile will not render.

Required Role in Tile Configuration Dialog

To make this work in Angular, we've made the following changes to our code:

• In the MVC controller, LoadDashboard now includes a list of all system roles in the dashboard object it returns. In our test project, these names are hard-coded; in a real application, they should be supplied by the authorization system. It also returns a filtered list of queries; any queries that require a role the current user doesn't have are not included.
Dashboard dashboard = new Dashboard()
{
    DashboardName = "Home",
    Username = username,
    IsAdmin = CurrentUserIsAdmin(Request),
    Tiles = new List<tile>(),
    Queries = new List<dashboardquery>(),
    Roles = new List<string>(),
    IsDefault = false
};

dashboard.Roles.Add("Accounting");
dashboard.Roles.Add("Admin");
dashboard.Roles.Add("Employee");
dashboard.Roles.Add("Executive");
dashboard.Roles.Add("Manager");
dashboard.Roles.Add("Marketing");
dashboard.Roles.Add("Manufacturing");
dashboard.Roles.Add("Sales");

...

using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["Database"]))
{
    conn.Open();

    // Load queries.

    DashboardQuery dashboardQuery = null;

    String query = "SELECT * FROM DashboardQuery ORDER BY Name";

    dashboard.Queries.Add(new DashboardQuery()
        {
            QueryName = "inline",
            ValueType = "number",
            Role = ""
        });

    bool addQuery = false;
    String[] roles = CurrentUserRoles(Request);

    using (SqlCommand cmd = new SqlCommand(query, conn))
    {
        using(SqlDataReader reader = cmd.ExecuteReader())
        {
            while(reader.Read())
            {
                dashboardQuery = new DashboardQuery()
                {
                        QueryName = Convert.ToString(reader["Name"]),
                        ValueType = Convert.ToString(reader["ValueType"]),
                        Role = Convert.ToString(reader["Role"])
                };

                addQuery = true;
                if (!String.IsNullOrEmpty(dashboardQuery.Role)) // don't add query if it requires a role the user doesn't have
                {
                    if (roles != null)
                    {
                        addQuery = false;
                        foreach(String role in roles)
                        {
                            if (role==dashboardQuery.Role)
                            {
                                addQuery = true;
                                break;
                            }
                        }
                    }
                }

                if (addQuery)
                {
                    dashboard.Queries.Add(dashboardQuery);
                }
            }
        }
    }

MVC Controller C# LoadDashboard code to return  master role list

• The MVC controller GetUser function returns the user's roles
// /Dashboard/GetUser .... returns username and admin privilege of cucrrent user.

[HttpGet]
public JsonResult GetUser()
{
// If ?user=<username> specified, set username and create cookie
String username = null; // = Request.QueryString["user"];
if (String.IsNullOrEmpty(username)) // if nothing specified in URL, ...
{
    // ...Check for existing username cookie
    if (Request != null && Request.Cookies.AllKeys.Contains("dashboard-username"))
    {
        username = Request.Cookies["dashboard-username"].Value;
    }
    else
    {
        username = "john.smith";    // else default john.smith
        HttpCookie cookie = new HttpCookie("dashboard-username");   // Set cookie
        cookie.Value = username;
        Response.Cookies.Add(cookie);
    }
}
else
{
    HttpCookie cookie = new HttpCookie("dashboard-username");   // Set cookie
    cookie.Value = username;
    Response.Cookies.Add(cookie);
}

User user = new User()
{
    Username = CurrentUsername(Request),
    Roles = CurrentUserRoles(Request),
    IsAdmin = CurrentUserIsAdmin(Request)
};
return Json(user, JsonRequestBehavior.AllowGet);
}

MVC Controller C# GetUser code to return user roles

• The Data Service passes the roles to the controller, which holds the list in a roles variable.
// Load tile definitions and perform remaining initilization.

self.LoadDashboard = function () {
    if (!DataService.requiresPromise) {
        self.tiles = DataService.getTileLayout();
        self.queries = DataService.queries;
        self.roles = DataService.roles;
Angular controller storing queries in LoadDashboard

• The Angular controller's ComputeLayout function now sets a hidden flag on each tile. A tile is marked hidden if it requires a role the user does not have.
self.computeLayout = function () {
    if (self.tiles == null) return;

    var matrix = [];

    for (var r = 0; r < self.tilesdown; r++) {
        matrix.push([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // support up to 20 tile units across 
    }

    var numcols = self.tablecolumns();
    if (numcols < 1) numcols = 1;

    // This is used in template to render things like table <col> elements.
    self.tilesacross = numcols;
    self.tileunits = [];
    for (var u = 0; u < numcols; u++) {
        self.tileunits.push(u);
    }

    // set tile.hidden for each tile based on role assignments.

    var tile = null;
    for (var t = 0; t < self.tiles.length; t++) {
        tile = self.tiles[t];
        tile.hidden = false;
        if (tile.role) {
            if (!self.userInRole(tile.role)) {
                tile.hidden = true;
            }
        }
    }
Angular ComputeLayout function code to mark unauthorized tiles hidden 

• Lastly, the HTML template markup has an ng-if condition (line 2) which will skip over rendering a tile is tile.hidden is true.
                <!-- Populated tile (data loaded) -->
                <div id="tile-{{tile.id}}" ng-if="tile.haveData && !tile.hidden"
                     class="tile" ng-class="tile.classes" ng-style="{ 'background-color': $ctrl.tileColor(tile.id), 'color': $ctrl.tileTextColor(tile.id), 'top': $ctrl.tileY(tile.id), 'left': $ctrl.tileX(tile.id), 'border': ($ctrl.configIndex==$index)?'dotted':'none', 'border-color': ($ctrl.configIndex==$index)?'white':'transparent' }"
                     style="overflow: hidden; position: absolute; display: inline-block"
                     draggable="true" ondragstart="tile_dragstart(event);"
                     ondrop="tile_drop(event);" ondragover="tile_dragover(event);">
                    <div class="dropdown" style="height: 100%">
                        <!-- tile menu -->
                        <div class="hovermenu">
                            <a href="javascript:void(0)" class="dropdown-toggle" style="text-decoration: none; color: inherit" data-toggle="dropdown">
                                <i class="fa fa-ellipsis-h" aria-hidden="true"></i>
                            </a>
                            <ul class="dropdown-menu" style="margin-top: -10px; margin-left:-144px !important; font-size: 16px !important">
                                <li><a id="tile-config-{{tile.id}}" href="#" onclick="configureTile(this.id);"><i class="fa fa-gear" aria-hidden="true"></i>  Configure Tile</a></li>
                                <li><a id="tile-config-{{tile.id}}" href="#" onclick="copyTile(this.id);"><i class="fa fa-clone" aria-hidden="true"></i>  Copy Tile</a></li>
                                <li><a id=tile-remove-{{tile.id}}" href="#" onclick="removeTileConfirm(this.id);"><i class="fa fa-trash-o" aria-hidden="true"></i>  Remove Tile</a></li>
                            </ul>
                        </div>
                        <a id="config-{{tile.id}}" ng-href="{{$ctrl.rearranging ? null : tile.link}}" style="color: inherit; text-decoration: inherit;">
                            <div style="overflow: hidden; white-space: nowrap"> {{tile.title}}</div>
                            <div style="position: relative; height: 100%">
                                <!-- COUNTER tile -->
                                <div ng-if="tile.type=='counter' && tile.height==1"
                                     style="text-align: center; position: absolute; left: 0; right: 0; margin: 0 auto; top: 25px">
                                    <div style="font-size: 72px">{{tile.value}}</div>
                                    <div style="font-size: 16px">{{tile.label}}</div>
                                </div>
HTML Markup code to Conditionally Render Tiles

Personalized Tiles

Much of the information you might track in a business dashboard--such as sales, orders, customers, inventory levels, etc.--is more useful to a user if it can be filtered to be personal. For example, imagine a tile that shows the count of orders, or a table tile listing open orders. If you're a salesperson, you would probably be more interested in those tiles if they listed your orders.

To support personalization, we'll make it possible for our data queries (stored in the DashboardQuery database table) to reference the current user's username. The symbol @username in a query will be automatically replaced by the current user name when the MVC controller executes a data query.

For example, we've previously shown an Orders counter tile that uses the Order Count data query. If instead we wanted a My Orders counter tile, we can ceate an Order Count (My Orders) query backed by this query:

SELECT COUNT(ord.OrderId) FROM [Order] ord INNER JOIN Employee emp ON emp.EmployeeId=ord.SalesPersonEmployeeId AND emp.Username=@username

We can then use this personalized query to define a My Orders tile, limited to the Sales role.

Personalized Tile My Orders

The resulting tile will show different results based on the current user:

My Orders tile for stuart.downey (a salesman)


My Orders tile for john.smith (an admin, no order)

(no tile displayed)
My Orders tile for marcia.brady (not in Sales role, tile not visible)

Roles in Action

Now it's time to see this role support in action. Imagine you are HRAdmin John Smith, and you have just created the following default dashboard for employees:
  1. A Customers counter tile, showing the count of customers. Available to all.
  2. An Orders counter tile, showing the count of orders. Available to all.
  3. A My Orders counter tile, showing the current user's order count. Restricted to Sales.
  4. A Customer Satisfaction KPI tile, showing average customer rating. Available to all.
  5. A My Open Orders table tile, listing the current user's open orders. Restricted to Sales.
  6. A Revenue Share by Store pie chart tile, showng revenue by store. Restricted to Sales.
  7. An Orders tile, listing all orders. Available to all.
  8. A Revenue by Store bar chart tile, showing revenue amounts by store. Restricted to Sales.
  9. A My Direct Reports table tile, showing current user's direct reports. Restricted to Manager.
Let's see how this dashboard is shown to different users, starting with our admin, John Smith. Because he is an admin, John gets to see all tiles. Because John is neither a manager nor a salesperson, the personalized tiles My Orders, My Open Orders, and My Direct Reports are empty as there is no data for John.

Default dashboard as viewed by Admin john.smith

Now, instead imagine the dashboard is being viewed by Stuart Downey, a sales executive who has the Sales role. His dashboard is shown below. Note he is seeing different data for his personalized tiles than John: he has direct reports, and he has orders.

Default dashboard as viewed by Sales Executive Stuart Downey

Finally, let's view the dashboard as Office Manager Marcia Brady. Marcia is not in the Sales role, so tiles like My Orders, My Direct Orders, Revenue Share by Store, and Revenue by Store don't appear. But she is a manager, so she does see her direct reports listed in the My Direct Reports tile.

Default dashboard as viewed by Office Manager Marcia Brady

Our role-based features are working well: users see only what they are authorized to see, and much of the information is personalized for their scope of interest.

To see this for yourself, download the sample project and database and follow the intstructions to use the SQL Server Data Service.

Summary

Today in Part 8 we achieved the following:

  • Improved the mobile experience
    • Made use of a meta viewport tag to set ideal page width on mobile devices
    • Changed the Rearrange Tiles implementation for mobile devices to use a reordering dialog
    • Adding a dashboard menu, and relocated some actions from the tile menu
    • Added a Copy Tile action to the tile menu
  • Added role support
    • Added the concept of multiple user logins and roles to the test project
    • Added support for default layouts for roles
    • Added ability to restrict a tile to a role
    • Added personalized tiles through the use of @username in data queries
In this update we've also made some progress on unit testing--but we're going to explore all that in Part 9.

AngularJS: How is it Holding Up?

And how are we feeling about AngularJS at this point? There's definitely good and bad:

  • Angular has some powerful directives (ng-if, ng-style, ng-repeat, etc.) that have been fun to leverage in our markup; however, some of these directives have quirks so occasionally this has been frustrating to get right.
  • Angular more or less forces you to modularize everything you do--you end up with separate controllers, services, templates. That's good. On the other hand, we are loading many  more discrete files now. It remains to be seen if we can take advantage of something like ASP.NET bundles to make loading of dependency JS files more efficient.
  • Angular is designed to facilitate user testing. In theory, our controller and our services, should all be easily testable. In practice, this is one of the things that has taken the longest to get working. There are a lot of caveats to writing Angular tests, which we'll get into next time.
  • There's a huge amount of online inormation and support for Angular. But, you get a lot of conflicting advice. Part of the reason for that is there's so much exposed in Angular in terms of layers, API, and JavaScript objects. There are many ways to do things. Perhaps that's good, in some ways, but when you're trying to get a problem solved it's frustrating to have to sort through dozens of suggestions and perspectives before you land on something that works.
So far, AngularJS has been useful but also frustrating at times.

Download Code
Dashboard_08.zip
https://drive.google.com/open?id=11bej1Wf_YmqqW0Saed-J0SfTy2ERR1Qu

Next: Blogged: An AngularJS Dashboard, Part 9: Unit Tests

No comments: