Demonstration of Total Profit/Loss amount of a company through WaterFall2d Fusion Chart with AngularJS and WebAPI

Rajnilari2015
Posted by in AngularJS 1x category on for Beginner level | Points: 250 | Views : 3313 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article, we will look into the integration of WaterFall2d Fusion Chart with AngularJS and WebAPI.


 Download source code for Demonstration of Total Profit/Loss amount of a company through WaterFall2d Fusion Chart with AngularJS and WebAPI

Introduction

Data Visualization is a very important aspect from the view point of an end user since it presents the visual representation of data. It brings clarity in communicating the information to the end users via the graphs, plots, tables, charts etc. It is through the application of proper and effective visualization that help users to analyze and reason about data and evidence which on the other hand brings more data accessibility, understand ability and thereby usability leading to make proper strategic decision.

FusionCharts, part of InfoSoft Global (P) Ltd, is privately held software provider of data visualization products (JavaScript Charts, Maps, Widgets and Dashboards).

In this article, we will look into the integration of WaterFall2d Fusion Chart with AngularJS and WebAPI.

What is Waterfall Charts?

Waterfall charts depicts how a value increases or decreases to come to a final value. The start and the end values are represented by whole columns, while the intermediate values are denoted by floating columns. The columns are usually color-coded for differentiating between positive and negative values.

Objective

Consider a scenario where say we want to figure out the Total Profit/Loss that a company made in a year. Let's say the Total Revenue = Product Revenue + Services Revenue. Also say the Total Costs = Fixed Costs + Variable Costs. So the Total Profit/Loss = Total Revenue - Total Costs.

Kindly note that, we will evaluate dynamically whether the company has made profit or loss.

If the Company has made profit then the final output should be as under

If the Company has made loss then the final output should be as under

Using the code

Let us first create the data structure

public class PL
{
    public string label { get; set; }
    public string value { get; set; }
    public string color { get; set; }
    public string issum { get; set; }
    public string cumulative { get; set; }
}

and then write the WebAPI as under

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebAPI2.Controllers
{
    public class PLReportController : ApiController
    {

        [Route("FusionChartReports/PLReportController")]
        public List<PL> GetACTReport()
        {
            var objPL = new List<PL>();

            //observe that the color codes are same for the revenues. 
            var productRevenues = new PL() { label = "Product Revenue", value = "20000", color = "#33ccff" };
            var servicesRevenues = new PL() { label = "Services Revenue", value = "10000", color = "#33ccff" };
            var totalRevenues = new PL() { label = "Total Revenue", color = "6baa01", issum = "1" };

            //observe that the color codes are same for the costs.

            var fixedCosts = new PL() { label = "Fixed Costs", value = "-15000", color = "#ff00ff" };
            var variableCosts = new PL() { label = "Variable Costs", value = "-6000", color = "#ff00ff" }; 
            
            /* uncomment for Loss
             
             var fixedCosts = new PL() { label = "Fixed Costs", value = "-25000", color = "#ff00ff" };
             var variableCosts = new PL() { label = "Variable Costs", value = "-10000", color = "#ff00ff" };             
             
             */
             
            var totalCosts = new PL() { label = "Total Costs", color = "e44a00", issum = "1", cumulative = "0" };

            //check if it is profit or loss for the company
            var sumRevenues = Convert.ToInt32(productRevenues.value) + Convert.ToInt32(servicesRevenues.value);
            var sumCosts = Convert.ToInt32(fixedCosts.value) + Convert.ToInt32(variableCosts.value);

            var pl = Math.Abs(sumRevenues) - Math.Abs(sumCosts) > 0 ? "Profit" : "Loss";
                        
            var totalPL = new PL() 
            { 
                label = pl == "Profit"? "Total Profit" : "Total Loss"
                ,
                color = pl == "Profit" ? "#0066ff" : "#e60000"
                , issum = "1"
                , cumulative = "1" 
            };

            objPL.Add(productRevenues);
            objPL.Add(servicesRevenues);
            objPL.Add(totalRevenues);

            objPL.Add(fixedCosts);
            objPL.Add(variableCosts);
            objPL.Add(totalCosts);

            objPL.Add(totalPL);

            return objPL;
        }


        /// <summary>
        /// Get the revenues
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private PL GetRevenues(params string[] arr)
        {
            var objRevenue = new PL();
            objRevenue.label = arr[0];
            objRevenue.value = arr[1];
            objRevenue.color = arr[2];
            return objRevenue;
        }
        
    }
}

When we ran this in PostMan, we receive the below JSON

Now, it's time to consume the web services through AngularJS and use the Fusion WaterFall2d Chart for the Data Visualization part.

For this to happen we will create a "PLReport.js" file where we will define the Module, Controller and the Service consumption.

var myApp = angular.module("myApp", []);
myApp.controller("PLReportController", function($scope, $http){

	$scope.displayChart = function(){

		FusionCharts.ready(function () {

		var plChart; //declare an object that will hold the instance of the FusionChart
		
		var chartLayout = {
					"caption": "Company Profit/Loss",
					"bgcolor": "FFFFFF",
					"numberprefix": "?",
					"showvalues": "1",
					"showplotborder": "0",
					"placevaluesinside": "1",
					"showsumatend": "0",
					"canvasborderthickness": "1",
					"canvasbordercolor": "B4BBC1",
					"canvasborderalpha": "0",
					"borderthickness": "1",
					"connectordashed": "1",
					"showborder": "0",
					"plotgradientcolor": " ",
					"showalternatehgridcolor": "0",
					"labeldisplay": "WRAP",
					"divlinecolor": "CCCCCC",
					"showcanvasborder": "0",
					"basefontcolor": "FFFFFF",
					"outcnvbasefontcolor": "#003399",
					"tooltipcolor": "#336600 "
				};
			
	//invoke the service			
	var promiseGet = $http.get("http://localhost:60422/FusionChartReports/PLReportController");

	promiseGet.then(function (promiseObj) {
							
					// binding the data
	$scope.dataSource = { 'chart' : chartLayout, 'data': promiseObj.data };

	plChart = new FusionCharts({
					type: 'waterfall2d',
					renderAt: 'chartContainer',												
					width: "800",
        				height: "500",
					dataFormat: 'json',
					dataSource : $scope.dataSource

			});

	//render the chart to the div which is chartContainer
	plChart.render("chartContainer");					
			},function (errorPl) { //if something went wrong
                  $log.error('failure loading the record', errorPl);
              }
          ); //end of promise object
		});//end Fusion Chart Ready Function
	}; //end function displayChart
}); //end controller

Here we are consuming the WebAPI by using the promise object and then merging the JSON in the way Fusion Chart needs that. The Fusion Data Source needs a)chart and b)data. The later is coming from the API.

Finally we need to bind the data. For this, let us create "PLReport.html" and add the below script

<!DOCTYPE html>
<html>
	<head>
	  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	  <title>Company Profit/Loss Report</title> 
	  <link href="css/custom.css" rel="stylesheet">
	  <link href="css/custom2.css" rel="stylesheet">  
	  <script data-require="angular.js@1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script> 
	  <script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
	  <script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.widgets.js"></script>     
	  <script type='text/javascript' src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
	  <script src="PLReport.js"></script>
	  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
	</head>
	<body ng-app="myApp"> 
		<div 
			id="chartContainer" 
			ng-controller="PLReportController" 
			align="center"  
			ng-init='displayChart()'>
		</div> 		 
	</body>
</html>

That's all we need to do for the complete integration.

N.B.~ This article assumes that users have previous experience in AngularJS and WebAPI. If not then here is a good point to start

  1. AngularJS How to tutorials
  2. CRUD Operation using Web API and MVC4

Conclusion

Hope this will be helpful. Thanks for reading the article. Zipped file attached.


N.B.~ This demo will work for free/trial as well as the paid version of Fusion Charts.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)