Extract and manipulate date from SharePoint and export into Google ChartsDate composition from day, month and year inputForecast maintenance interval for fleet of aircraftMake To and From date range picker using jQuery UIRead date from a file and rename two files using the dateGet rows from a table and add rows to google chartsExtract value from a database and populate objectsRead data from Google Sheets API and populate a classExtract a number from a consecutive range in a Google SheetUpdate SQL database, similar-but-different queries for each monthReading releases details from github and writing to google sheet file

Valid Badminton Score?

Is it correct to write "is not focus on"?

What will be the benefits of Brexit?

If a character can use a +X magic weapon as a spellcasting focus, does it add the bonus to spell attacks or spell save DCs?

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

Best way to store options for panels

Why did Kant, Hegel, and Adorno leave some words and phrases in the Greek alphabet?

What to do with wrong results in talks?

Should my PhD thesis be submitted under my legal name?

Failed to fetch jessie backports repository

How does a character multiclassing into warlock get a focus?

How can my private key be revealed if I use the same nonce while generating the signature?

Star/Wye electrical connection math symbol

Increase performance creating Mandelbrot set in python

Personal Teleportation as a Weapon

How to prove that the query oracle is unitary?

What would be the benefits of having both a state and local currencies?

Why are on-board computers allowed to change controls without notifying the pilots?

Your magic is very sketchy

Is there any reason not to eat food that's been dropped on the surface of the moon?

Is it okay / does it make sense for another player to join a running game of Munchkin?

Where in the Bible does the greeting ("Dominus Vobiscum") used at Mass come from?

Greatest common substring

How do I define a right arrow with bar in LaTeX?



Extract and manipulate date from SharePoint and export into Google Charts


Date composition from day, month and year inputForecast maintenance interval for fleet of aircraftMake To and From date range picker using jQuery UIRead date from a file and rename two files using the dateGet rows from a table and add rows to google chartsExtract value from a database and populate objectsRead data from Google Sheets API and populate a classExtract a number from a consecutive range in a Google SheetUpdate SQL database, similar-but-different queries for each monthReading releases details from github and writing to google sheet file













0












$begingroup$


I am extracting a list of data from a SharePoint library with CSOM, then manipulating the data to give some sort of visible statistic through Google Charts. The data is a list of each parent department in our company and how many pages they printed in the previous week. Some additional information kept is the ISO Week, the current fiscal Quarter based on the ISO Week and wither or not the entry is in the Current, Previous, or Outdated quarter (where Outdated) is just any date outside the current or previous Quarter.



Everything currently gives the expected output, however it feels very messy and there's repeated code in a few places. Right now we have two Google Charts that give the following statistics:



  1. Number of pages printed in the current Quarter (A sum of all entries for each department under "Current Quarter")

  2. Percentage if pages printed relative to the previous quarter: essentially ((per-day average this quarter) / (per-day average last quarter) - 1)*100

Here's an image of what the graphs currently look like: Pages printed per SBU. Please note, SBU is our term for "parent department" and the image is relatively large, so I've opted to just post the URL.



First there are 4 'helper' functions I've added to either Date or Array types. These are:



Date.prototype.getWeek, Date.prototype.getWeeksInYear, Date.prototype.getWeekQuarter, and Array.prototype.customSort and are outlined at the bottom of the script:



var listTitle = "Printing Stats"
var viewTitle = "Current Stats"
// var dictStats = ; // For testing

/*
* Get the list's view via CAML request.
* Prepares the body with a new DOM object to put charts in
* Takes no arguments
*/
function retrieveViewQuery()
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle(listTitle);
this.oView = oList.get_views().getByTitle(viewTitle);

var elem = document.createElement("div");
elem.id = "container";
document.querySelector(".ms-rte-layoutszone-inner").prepend(elem);

clientContext.load(oView);
clientContext.executeQueryAsync(
this.retrieveViewQuerySucceeded.bind(this),
this.onQueryFailed.bind(this)
);


function onQueryFailed(sender, args)
alert('Request failed. ' + args.get_message() + 'n' + args.get_stackTrace());


/*
* Get the items from the list via second CAML request.
*/
function retrieveViewQuerySucceeded(sender, args)
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle(listTitle);

var query = new SP.CamlQuery();
query.set_viewXml(this.oView.get_viewQuery());
this.items = oList.getItems(query);

clientContext.load(this.items);
clientContext.executeQueryAsync(
this.retrieveItemListSucceeded.bind(this),
this.onQueryFailed.bind(this)
);


/*
* Extract the the following parameters from the list:
* - Which quarter is it: "Previous Quarter" or "Current Quarter"
* - Which SBUs are present in the data
* - Extract the cumulative number of pages per quarter
* - Extract the week number of the quarter
*/
function retrieveItemListSucceeded(sender, args)
var dictStats = ;
var listItemEnumerator = items.getEnumerator();
var oListItem;

while (listItemEnumerator.moveNext())
oListItem = listItemEnumerator.get_current().get_fieldValues();
var quarter = oListItem.PreviousOrCurrentQuarter;
var itemTitle = oListItem.Title.replace(/s*-s*ZvL/i, "");

// Prepare datastructure
if (!dictStats[quarter])
dictStats[quarter] =

if (!dictStats[quarter][itemTitle])
dictStats[quarter][itemTitle] = [[0, 0]];


var tempItem = dictStats[quarter][itemTitle];
dictStats[quarter][itemTitle].push([
parseInt(tempItem[tempItem.length - 1]) + oListItem.TotalPrintedPages,
oListItem.RelevantDate
]);


chartStatSpecifications(dictStats);


/*
* Prepare the data for the chart views.
* Takes in an object with the following data structure:
* Object >
* Previous Quarter || Current Quarter >
* SBU >
* [ cumulativePageCountInQuarter, WeekOfQuarter]
*/
function chartStatSpecifications(allStats)
var itemStats = [[], []];
var totalPageCount = 0,
totalDeptAvgLQ = 0;

for (var dept in allStats["Current Quarter"])
var deptStats = allStats["Current Quarter"][dept.toString()];
var name = dept.toString().replace("&", "&rn");
var deptAvgLQ, deptAvgCQ;

// Calculate average pages printed so far this Quarter
// and overall last quarter based on ISO Weeks
if (allStats["Previous Quarter"] && allStats["Previous Quarter"][dept.toString()])
var tmp = allStats["Previous Quarter"][dept.toString()];
tmp = tmp[tmp.length - 1]

var weeks = (new Date(tmp[1])).getWeeksInYear() == 53 ? 14 : 13
deptAvgLQ = Math.ceil(parseInt(tmp[0]) / (weeks * 7));
console.log(weeks * 7); // For testing

weeks = (new Date(tmp[1])).getWeek() - ((new Date(tmp[1])).getWeekQuarter() - 1) * 13
deptAvgCQ = Math.ceil(parseInt(tmp[0]) / (weeks * 7));


// Total number of pages this quarter
itemStats[0].push([
name,
deptStats[deptStats.length - 1][0]
]);

// Percentage above last quarter's average
itemStats[1].push([
name,
Math.floor((deptAvgCQ / deptAvgLQ - 1) * 5000) / 50
]);

totalPageCount += deptStats[deptStats.length - 1][0];
totalDeptAvgLQ += deptAvgCQ;

totalPageCount = totalPageCount.toString().replace(/B(?=(d3)+(?!d))/g, " ");

totalDeptAvgLQ = Math.floor(totalDeptAvgLQ / itemStats[1].length * 50) / 50
totalDeptAvgLQ = totalDeptAvgLQ.toString().replace(/B(?=(d3)+(?!d))/g, " ");

itemStats[0].customSort(['SBU', 'Pages'], function (a, b)
return (a[1] - b[1])
);
google.charts.setOnLoadCallback(function ()
drawChart('Total Pages this Quarter: ' + totalPageCount, itemStats[0])
);

itemStats[1].customSort(['SBU', '% Above'], function (a, b)
return a[1] - b[1]
);
google.charts.setOnLoadCallback(function ()
drawChart('Percentage over last quarter's average: ', itemStats[1])
// drawChart('Percentage over last quarter's average: ' + totalDeptAvgLQ, itemStats[1])
);


/*
* Draw the Google Chart.
* Inputs:
* chartTitle :: Title for the chart
* stats :: Prepared data with 2 or more columns
*/
function drawChart(chartTitle, stats)
var data = google.visualization.arrayToDataTable(stats);
var options =
title: chartTitle,
legend: 'none',
height: 400
;

// Instantiate and draw the chart.
var elem = document.createElement("div");
document.getElementById('container').appendChild(elem);
var chart = new google.visualization.ColumnChart(elem);
chart.draw(data, options);


SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveViewQuery);

/*
* * * * * * Additional Scripting tools * * * * * *
*
* This script is released to the public domain and may be used, modified and
* distributed without restrictions. Attribution not necessary but appreciated.
* Source: https://weeknumber.net/how-to/javascript
*
* Returns the ISO week of the date.
*/
Date.prototype.getWeek = function ()
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 -
3 + (week1.getDay() + 6) % 7) / 7);


// Returns the four-digit year corresponding to the ISO week of the date.
Date.prototype.getWeeksInYear = function ()

// Returns how many weeks are in a date's specified quarter
Date.prototype.getWeekQuarter = function ()
var date = new Date(this.getTime());
weekNum = date.getWeek();
return weekNum == 53 ? 4 : Math.ceil(weekNum / 13);


// Takes an array and directly manipulates the object with a specified sort
// prepends a smaller object to the array
Array.prototype.customSort = function (prependItem, customSort)
this.sort(customSort);
if (prependItem)
this.unshift(prependItem);
return this;



And below is added to the SharePoint page so Google Charts can be loaded:



<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"></script>
<script type = "text/javascript">
google.charts.load('current', packages: ['corechart']);
</script>








share







New contributor




KGlasier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$
















    0












    $begingroup$


    I am extracting a list of data from a SharePoint library with CSOM, then manipulating the data to give some sort of visible statistic through Google Charts. The data is a list of each parent department in our company and how many pages they printed in the previous week. Some additional information kept is the ISO Week, the current fiscal Quarter based on the ISO Week and wither or not the entry is in the Current, Previous, or Outdated quarter (where Outdated) is just any date outside the current or previous Quarter.



    Everything currently gives the expected output, however it feels very messy and there's repeated code in a few places. Right now we have two Google Charts that give the following statistics:



    1. Number of pages printed in the current Quarter (A sum of all entries for each department under "Current Quarter")

    2. Percentage if pages printed relative to the previous quarter: essentially ((per-day average this quarter) / (per-day average last quarter) - 1)*100

    Here's an image of what the graphs currently look like: Pages printed per SBU. Please note, SBU is our term for "parent department" and the image is relatively large, so I've opted to just post the URL.



    First there are 4 'helper' functions I've added to either Date or Array types. These are:



    Date.prototype.getWeek, Date.prototype.getWeeksInYear, Date.prototype.getWeekQuarter, and Array.prototype.customSort and are outlined at the bottom of the script:



    var listTitle = "Printing Stats"
    var viewTitle = "Current Stats"
    // var dictStats = ; // For testing

    /*
    * Get the list's view via CAML request.
    * Prepares the body with a new DOM object to put charts in
    * Takes no arguments
    */
    function retrieveViewQuery()
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle(listTitle);
    this.oView = oList.get_views().getByTitle(viewTitle);

    var elem = document.createElement("div");
    elem.id = "container";
    document.querySelector(".ms-rte-layoutszone-inner").prepend(elem);

    clientContext.load(oView);
    clientContext.executeQueryAsync(
    this.retrieveViewQuerySucceeded.bind(this),
    this.onQueryFailed.bind(this)
    );


    function onQueryFailed(sender, args)
    alert('Request failed. ' + args.get_message() + 'n' + args.get_stackTrace());


    /*
    * Get the items from the list via second CAML request.
    */
    function retrieveViewQuerySucceeded(sender, args)
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle(listTitle);

    var query = new SP.CamlQuery();
    query.set_viewXml(this.oView.get_viewQuery());
    this.items = oList.getItems(query);

    clientContext.load(this.items);
    clientContext.executeQueryAsync(
    this.retrieveItemListSucceeded.bind(this),
    this.onQueryFailed.bind(this)
    );


    /*
    * Extract the the following parameters from the list:
    * - Which quarter is it: "Previous Quarter" or "Current Quarter"
    * - Which SBUs are present in the data
    * - Extract the cumulative number of pages per quarter
    * - Extract the week number of the quarter
    */
    function retrieveItemListSucceeded(sender, args)
    var dictStats = ;
    var listItemEnumerator = items.getEnumerator();
    var oListItem;

    while (listItemEnumerator.moveNext())
    oListItem = listItemEnumerator.get_current().get_fieldValues();
    var quarter = oListItem.PreviousOrCurrentQuarter;
    var itemTitle = oListItem.Title.replace(/s*-s*ZvL/i, "");

    // Prepare datastructure
    if (!dictStats[quarter])
    dictStats[quarter] =

    if (!dictStats[quarter][itemTitle])
    dictStats[quarter][itemTitle] = [[0, 0]];


    var tempItem = dictStats[quarter][itemTitle];
    dictStats[quarter][itemTitle].push([
    parseInt(tempItem[tempItem.length - 1]) + oListItem.TotalPrintedPages,
    oListItem.RelevantDate
    ]);


    chartStatSpecifications(dictStats);


    /*
    * Prepare the data for the chart views.
    * Takes in an object with the following data structure:
    * Object >
    * Previous Quarter || Current Quarter >
    * SBU >
    * [ cumulativePageCountInQuarter, WeekOfQuarter]
    */
    function chartStatSpecifications(allStats)
    var itemStats = [[], []];
    var totalPageCount = 0,
    totalDeptAvgLQ = 0;

    for (var dept in allStats["Current Quarter"])
    var deptStats = allStats["Current Quarter"][dept.toString()];
    var name = dept.toString().replace("&", "&rn");
    var deptAvgLQ, deptAvgCQ;

    // Calculate average pages printed so far this Quarter
    // and overall last quarter based on ISO Weeks
    if (allStats["Previous Quarter"] && allStats["Previous Quarter"][dept.toString()])
    var tmp = allStats["Previous Quarter"][dept.toString()];
    tmp = tmp[tmp.length - 1]

    var weeks = (new Date(tmp[1])).getWeeksInYear() == 53 ? 14 : 13
    deptAvgLQ = Math.ceil(parseInt(tmp[0]) / (weeks * 7));
    console.log(weeks * 7); // For testing

    weeks = (new Date(tmp[1])).getWeek() - ((new Date(tmp[1])).getWeekQuarter() - 1) * 13
    deptAvgCQ = Math.ceil(parseInt(tmp[0]) / (weeks * 7));


    // Total number of pages this quarter
    itemStats[0].push([
    name,
    deptStats[deptStats.length - 1][0]
    ]);

    // Percentage above last quarter's average
    itemStats[1].push([
    name,
    Math.floor((deptAvgCQ / deptAvgLQ - 1) * 5000) / 50
    ]);

    totalPageCount += deptStats[deptStats.length - 1][0];
    totalDeptAvgLQ += deptAvgCQ;

    totalPageCount = totalPageCount.toString().replace(/B(?=(d3)+(?!d))/g, " ");

    totalDeptAvgLQ = Math.floor(totalDeptAvgLQ / itemStats[1].length * 50) / 50
    totalDeptAvgLQ = totalDeptAvgLQ.toString().replace(/B(?=(d3)+(?!d))/g, " ");

    itemStats[0].customSort(['SBU', 'Pages'], function (a, b)
    return (a[1] - b[1])
    );
    google.charts.setOnLoadCallback(function ()
    drawChart('Total Pages this Quarter: ' + totalPageCount, itemStats[0])
    );

    itemStats[1].customSort(['SBU', '% Above'], function (a, b)
    return a[1] - b[1]
    );
    google.charts.setOnLoadCallback(function ()
    drawChart('Percentage over last quarter's average: ', itemStats[1])
    // drawChart('Percentage over last quarter's average: ' + totalDeptAvgLQ, itemStats[1])
    );


    /*
    * Draw the Google Chart.
    * Inputs:
    * chartTitle :: Title for the chart
    * stats :: Prepared data with 2 or more columns
    */
    function drawChart(chartTitle, stats)
    var data = google.visualization.arrayToDataTable(stats);
    var options =
    title: chartTitle,
    legend: 'none',
    height: 400
    ;

    // Instantiate and draw the chart.
    var elem = document.createElement("div");
    document.getElementById('container').appendChild(elem);
    var chart = new google.visualization.ColumnChart(elem);
    chart.draw(data, options);


    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveViewQuery);

    /*
    * * * * * * Additional Scripting tools * * * * * *
    *
    * This script is released to the public domain and may be used, modified and
    * distributed without restrictions. Attribution not necessary but appreciated.
    * Source: https://weeknumber.net/how-to/javascript
    *
    * Returns the ISO week of the date.
    */
    Date.prototype.getWeek = function ()
    var date = new Date(this.getTime());
    date.setHours(0, 0, 0, 0);
    // Thursday in current week decides the year.
    date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
    // January 4 is always in week 1.
    var week1 = new Date(date.getFullYear(), 0, 4);
    // Adjust to Thursday in week 1 and count number of weeks from date to week1.
    return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 -
    3 + (week1.getDay() + 6) % 7) / 7);


    // Returns the four-digit year corresponding to the ISO week of the date.
    Date.prototype.getWeeksInYear = function ()

    // Returns how many weeks are in a date's specified quarter
    Date.prototype.getWeekQuarter = function ()
    var date = new Date(this.getTime());
    weekNum = date.getWeek();
    return weekNum == 53 ? 4 : Math.ceil(weekNum / 13);


    // Takes an array and directly manipulates the object with a specified sort
    // prepends a smaller object to the array
    Array.prototype.customSort = function (prependItem, customSort)
    this.sort(customSort);
    if (prependItem)
    this.unshift(prependItem);
    return this;



    And below is added to the SharePoint page so Google Charts can be loaded:



    <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"></script>
    <script type = "text/javascript">
    google.charts.load('current', packages: ['corechart']);
    </script>








    share







    New contributor




    KGlasier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$














      0












      0








      0





      $begingroup$


      I am extracting a list of data from a SharePoint library with CSOM, then manipulating the data to give some sort of visible statistic through Google Charts. The data is a list of each parent department in our company and how many pages they printed in the previous week. Some additional information kept is the ISO Week, the current fiscal Quarter based on the ISO Week and wither or not the entry is in the Current, Previous, or Outdated quarter (where Outdated) is just any date outside the current or previous Quarter.



      Everything currently gives the expected output, however it feels very messy and there's repeated code in a few places. Right now we have two Google Charts that give the following statistics:



      1. Number of pages printed in the current Quarter (A sum of all entries for each department under "Current Quarter")

      2. Percentage if pages printed relative to the previous quarter: essentially ((per-day average this quarter) / (per-day average last quarter) - 1)*100

      Here's an image of what the graphs currently look like: Pages printed per SBU. Please note, SBU is our term for "parent department" and the image is relatively large, so I've opted to just post the URL.



      First there are 4 'helper' functions I've added to either Date or Array types. These are:



      Date.prototype.getWeek, Date.prototype.getWeeksInYear, Date.prototype.getWeekQuarter, and Array.prototype.customSort and are outlined at the bottom of the script:



      var listTitle = "Printing Stats"
      var viewTitle = "Current Stats"
      // var dictStats = ; // For testing

      /*
      * Get the list's view via CAML request.
      * Prepares the body with a new DOM object to put charts in
      * Takes no arguments
      */
      function retrieveViewQuery()
      var clientContext = new SP.ClientContext.get_current();
      var oList = clientContext.get_web().get_lists().getByTitle(listTitle);
      this.oView = oList.get_views().getByTitle(viewTitle);

      var elem = document.createElement("div");
      elem.id = "container";
      document.querySelector(".ms-rte-layoutszone-inner").prepend(elem);

      clientContext.load(oView);
      clientContext.executeQueryAsync(
      this.retrieveViewQuerySucceeded.bind(this),
      this.onQueryFailed.bind(this)
      );


      function onQueryFailed(sender, args)
      alert('Request failed. ' + args.get_message() + 'n' + args.get_stackTrace());


      /*
      * Get the items from the list via second CAML request.
      */
      function retrieveViewQuerySucceeded(sender, args)
      var clientContext = new SP.ClientContext.get_current();
      var oList = clientContext.get_web().get_lists().getByTitle(listTitle);

      var query = new SP.CamlQuery();
      query.set_viewXml(this.oView.get_viewQuery());
      this.items = oList.getItems(query);

      clientContext.load(this.items);
      clientContext.executeQueryAsync(
      this.retrieveItemListSucceeded.bind(this),
      this.onQueryFailed.bind(this)
      );


      /*
      * Extract the the following parameters from the list:
      * - Which quarter is it: "Previous Quarter" or "Current Quarter"
      * - Which SBUs are present in the data
      * - Extract the cumulative number of pages per quarter
      * - Extract the week number of the quarter
      */
      function retrieveItemListSucceeded(sender, args)
      var dictStats = ;
      var listItemEnumerator = items.getEnumerator();
      var oListItem;

      while (listItemEnumerator.moveNext())
      oListItem = listItemEnumerator.get_current().get_fieldValues();
      var quarter = oListItem.PreviousOrCurrentQuarter;
      var itemTitle = oListItem.Title.replace(/s*-s*ZvL/i, "");

      // Prepare datastructure
      if (!dictStats[quarter])
      dictStats[quarter] =

      if (!dictStats[quarter][itemTitle])
      dictStats[quarter][itemTitle] = [[0, 0]];


      var tempItem = dictStats[quarter][itemTitle];
      dictStats[quarter][itemTitle].push([
      parseInt(tempItem[tempItem.length - 1]) + oListItem.TotalPrintedPages,
      oListItem.RelevantDate
      ]);


      chartStatSpecifications(dictStats);


      /*
      * Prepare the data for the chart views.
      * Takes in an object with the following data structure:
      * Object >
      * Previous Quarter || Current Quarter >
      * SBU >
      * [ cumulativePageCountInQuarter, WeekOfQuarter]
      */
      function chartStatSpecifications(allStats)
      var itemStats = [[], []];
      var totalPageCount = 0,
      totalDeptAvgLQ = 0;

      for (var dept in allStats["Current Quarter"])
      var deptStats = allStats["Current Quarter"][dept.toString()];
      var name = dept.toString().replace("&", "&rn");
      var deptAvgLQ, deptAvgCQ;

      // Calculate average pages printed so far this Quarter
      // and overall last quarter based on ISO Weeks
      if (allStats["Previous Quarter"] && allStats["Previous Quarter"][dept.toString()])
      var tmp = allStats["Previous Quarter"][dept.toString()];
      tmp = tmp[tmp.length - 1]

      var weeks = (new Date(tmp[1])).getWeeksInYear() == 53 ? 14 : 13
      deptAvgLQ = Math.ceil(parseInt(tmp[0]) / (weeks * 7));
      console.log(weeks * 7); // For testing

      weeks = (new Date(tmp[1])).getWeek() - ((new Date(tmp[1])).getWeekQuarter() - 1) * 13
      deptAvgCQ = Math.ceil(parseInt(tmp[0]) / (weeks * 7));


      // Total number of pages this quarter
      itemStats[0].push([
      name,
      deptStats[deptStats.length - 1][0]
      ]);

      // Percentage above last quarter's average
      itemStats[1].push([
      name,
      Math.floor((deptAvgCQ / deptAvgLQ - 1) * 5000) / 50
      ]);

      totalPageCount += deptStats[deptStats.length - 1][0];
      totalDeptAvgLQ += deptAvgCQ;

      totalPageCount = totalPageCount.toString().replace(/B(?=(d3)+(?!d))/g, " ");

      totalDeptAvgLQ = Math.floor(totalDeptAvgLQ / itemStats[1].length * 50) / 50
      totalDeptAvgLQ = totalDeptAvgLQ.toString().replace(/B(?=(d3)+(?!d))/g, " ");

      itemStats[0].customSort(['SBU', 'Pages'], function (a, b)
      return (a[1] - b[1])
      );
      google.charts.setOnLoadCallback(function ()
      drawChart('Total Pages this Quarter: ' + totalPageCount, itemStats[0])
      );

      itemStats[1].customSort(['SBU', '% Above'], function (a, b)
      return a[1] - b[1]
      );
      google.charts.setOnLoadCallback(function ()
      drawChart('Percentage over last quarter's average: ', itemStats[1])
      // drawChart('Percentage over last quarter's average: ' + totalDeptAvgLQ, itemStats[1])
      );


      /*
      * Draw the Google Chart.
      * Inputs:
      * chartTitle :: Title for the chart
      * stats :: Prepared data with 2 or more columns
      */
      function drawChart(chartTitle, stats)
      var data = google.visualization.arrayToDataTable(stats);
      var options =
      title: chartTitle,
      legend: 'none',
      height: 400
      ;

      // Instantiate and draw the chart.
      var elem = document.createElement("div");
      document.getElementById('container').appendChild(elem);
      var chart = new google.visualization.ColumnChart(elem);
      chart.draw(data, options);


      SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveViewQuery);

      /*
      * * * * * * Additional Scripting tools * * * * * *
      *
      * This script is released to the public domain and may be used, modified and
      * distributed without restrictions. Attribution not necessary but appreciated.
      * Source: https://weeknumber.net/how-to/javascript
      *
      * Returns the ISO week of the date.
      */
      Date.prototype.getWeek = function ()
      var date = new Date(this.getTime());
      date.setHours(0, 0, 0, 0);
      // Thursday in current week decides the year.
      date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
      // January 4 is always in week 1.
      var week1 = new Date(date.getFullYear(), 0, 4);
      // Adjust to Thursday in week 1 and count number of weeks from date to week1.
      return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 -
      3 + (week1.getDay() + 6) % 7) / 7);


      // Returns the four-digit year corresponding to the ISO week of the date.
      Date.prototype.getWeeksInYear = function ()

      // Returns how many weeks are in a date's specified quarter
      Date.prototype.getWeekQuarter = function ()
      var date = new Date(this.getTime());
      weekNum = date.getWeek();
      return weekNum == 53 ? 4 : Math.ceil(weekNum / 13);


      // Takes an array and directly manipulates the object with a specified sort
      // prepends a smaller object to the array
      Array.prototype.customSort = function (prependItem, customSort)
      this.sort(customSort);
      if (prependItem)
      this.unshift(prependItem);
      return this;



      And below is added to the SharePoint page so Google Charts can be loaded:



      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"></script>
      <script type = "text/javascript">
      google.charts.load('current', packages: ['corechart']);
      </script>








      share







      New contributor




      KGlasier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I am extracting a list of data from a SharePoint library with CSOM, then manipulating the data to give some sort of visible statistic through Google Charts. The data is a list of each parent department in our company and how many pages they printed in the previous week. Some additional information kept is the ISO Week, the current fiscal Quarter based on the ISO Week and wither or not the entry is in the Current, Previous, or Outdated quarter (where Outdated) is just any date outside the current or previous Quarter.



      Everything currently gives the expected output, however it feels very messy and there's repeated code in a few places. Right now we have two Google Charts that give the following statistics:



      1. Number of pages printed in the current Quarter (A sum of all entries for each department under "Current Quarter")

      2. Percentage if pages printed relative to the previous quarter: essentially ((per-day average this quarter) / (per-day average last quarter) - 1)*100

      Here's an image of what the graphs currently look like: Pages printed per SBU. Please note, SBU is our term for "parent department" and the image is relatively large, so I've opted to just post the URL.



      First there are 4 'helper' functions I've added to either Date or Array types. These are:



      Date.prototype.getWeek, Date.prototype.getWeeksInYear, Date.prototype.getWeekQuarter, and Array.prototype.customSort and are outlined at the bottom of the script:



      var listTitle = "Printing Stats"
      var viewTitle = "Current Stats"
      // var dictStats = ; // For testing

      /*
      * Get the list's view via CAML request.
      * Prepares the body with a new DOM object to put charts in
      * Takes no arguments
      */
      function retrieveViewQuery()
      var clientContext = new SP.ClientContext.get_current();
      var oList = clientContext.get_web().get_lists().getByTitle(listTitle);
      this.oView = oList.get_views().getByTitle(viewTitle);

      var elem = document.createElement("div");
      elem.id = "container";
      document.querySelector(".ms-rte-layoutszone-inner").prepend(elem);

      clientContext.load(oView);
      clientContext.executeQueryAsync(
      this.retrieveViewQuerySucceeded.bind(this),
      this.onQueryFailed.bind(this)
      );


      function onQueryFailed(sender, args)
      alert('Request failed. ' + args.get_message() + 'n' + args.get_stackTrace());


      /*
      * Get the items from the list via second CAML request.
      */
      function retrieveViewQuerySucceeded(sender, args)
      var clientContext = new SP.ClientContext.get_current();
      var oList = clientContext.get_web().get_lists().getByTitle(listTitle);

      var query = new SP.CamlQuery();
      query.set_viewXml(this.oView.get_viewQuery());
      this.items = oList.getItems(query);

      clientContext.load(this.items);
      clientContext.executeQueryAsync(
      this.retrieveItemListSucceeded.bind(this),
      this.onQueryFailed.bind(this)
      );


      /*
      * Extract the the following parameters from the list:
      * - Which quarter is it: "Previous Quarter" or "Current Quarter"
      * - Which SBUs are present in the data
      * - Extract the cumulative number of pages per quarter
      * - Extract the week number of the quarter
      */
      function retrieveItemListSucceeded(sender, args)
      var dictStats = ;
      var listItemEnumerator = items.getEnumerator();
      var oListItem;

      while (listItemEnumerator.moveNext())
      oListItem = listItemEnumerator.get_current().get_fieldValues();
      var quarter = oListItem.PreviousOrCurrentQuarter;
      var itemTitle = oListItem.Title.replace(/s*-s*ZvL/i, "");

      // Prepare datastructure
      if (!dictStats[quarter])
      dictStats[quarter] =

      if (!dictStats[quarter][itemTitle])
      dictStats[quarter][itemTitle] = [[0, 0]];


      var tempItem = dictStats[quarter][itemTitle];
      dictStats[quarter][itemTitle].push([
      parseInt(tempItem[tempItem.length - 1]) + oListItem.TotalPrintedPages,
      oListItem.RelevantDate
      ]);


      chartStatSpecifications(dictStats);


      /*
      * Prepare the data for the chart views.
      * Takes in an object with the following data structure:
      * Object >
      * Previous Quarter || Current Quarter >
      * SBU >
      * [ cumulativePageCountInQuarter, WeekOfQuarter]
      */
      function chartStatSpecifications(allStats)
      var itemStats = [[], []];
      var totalPageCount = 0,
      totalDeptAvgLQ = 0;

      for (var dept in allStats["Current Quarter"])
      var deptStats = allStats["Current Quarter"][dept.toString()];
      var name = dept.toString().replace("&", "&rn");
      var deptAvgLQ, deptAvgCQ;

      // Calculate average pages printed so far this Quarter
      // and overall last quarter based on ISO Weeks
      if (allStats["Previous Quarter"] && allStats["Previous Quarter"][dept.toString()])
      var tmp = allStats["Previous Quarter"][dept.toString()];
      tmp = tmp[tmp.length - 1]

      var weeks = (new Date(tmp[1])).getWeeksInYear() == 53 ? 14 : 13
      deptAvgLQ = Math.ceil(parseInt(tmp[0]) / (weeks * 7));
      console.log(weeks * 7); // For testing

      weeks = (new Date(tmp[1])).getWeek() - ((new Date(tmp[1])).getWeekQuarter() - 1) * 13
      deptAvgCQ = Math.ceil(parseInt(tmp[0]) / (weeks * 7));


      // Total number of pages this quarter
      itemStats[0].push([
      name,
      deptStats[deptStats.length - 1][0]
      ]);

      // Percentage above last quarter's average
      itemStats[1].push([
      name,
      Math.floor((deptAvgCQ / deptAvgLQ - 1) * 5000) / 50
      ]);

      totalPageCount += deptStats[deptStats.length - 1][0];
      totalDeptAvgLQ += deptAvgCQ;

      totalPageCount = totalPageCount.toString().replace(/B(?=(d3)+(?!d))/g, " ");

      totalDeptAvgLQ = Math.floor(totalDeptAvgLQ / itemStats[1].length * 50) / 50
      totalDeptAvgLQ = totalDeptAvgLQ.toString().replace(/B(?=(d3)+(?!d))/g, " ");

      itemStats[0].customSort(['SBU', 'Pages'], function (a, b)
      return (a[1] - b[1])
      );
      google.charts.setOnLoadCallback(function ()
      drawChart('Total Pages this Quarter: ' + totalPageCount, itemStats[0])
      );

      itemStats[1].customSort(['SBU', '% Above'], function (a, b)
      return a[1] - b[1]
      );
      google.charts.setOnLoadCallback(function ()
      drawChart('Percentage over last quarter's average: ', itemStats[1])
      // drawChart('Percentage over last quarter's average: ' + totalDeptAvgLQ, itemStats[1])
      );


      /*
      * Draw the Google Chart.
      * Inputs:
      * chartTitle :: Title for the chart
      * stats :: Prepared data with 2 or more columns
      */
      function drawChart(chartTitle, stats)
      var data = google.visualization.arrayToDataTable(stats);
      var options =
      title: chartTitle,
      legend: 'none',
      height: 400
      ;

      // Instantiate and draw the chart.
      var elem = document.createElement("div");
      document.getElementById('container').appendChild(elem);
      var chart = new google.visualization.ColumnChart(elem);
      chart.draw(data, options);


      SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveViewQuery);

      /*
      * * * * * * Additional Scripting tools * * * * * *
      *
      * This script is released to the public domain and may be used, modified and
      * distributed without restrictions. Attribution not necessary but appreciated.
      * Source: https://weeknumber.net/how-to/javascript
      *
      * Returns the ISO week of the date.
      */
      Date.prototype.getWeek = function ()
      var date = new Date(this.getTime());
      date.setHours(0, 0, 0, 0);
      // Thursday in current week decides the year.
      date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
      // January 4 is always in week 1.
      var week1 = new Date(date.getFullYear(), 0, 4);
      // Adjust to Thursday in week 1 and count number of weeks from date to week1.
      return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 -
      3 + (week1.getDay() + 6) % 7) / 7);


      // Returns the four-digit year corresponding to the ISO week of the date.
      Date.prototype.getWeeksInYear = function ()

      // Returns how many weeks are in a date's specified quarter
      Date.prototype.getWeekQuarter = function ()
      var date = new Date(this.getTime());
      weekNum = date.getWeek();
      return weekNum == 53 ? 4 : Math.ceil(weekNum / 13);


      // Takes an array and directly manipulates the object with a specified sort
      // prepends a smaller object to the array
      Array.prototype.customSort = function (prependItem, customSort)
      this.sort(customSort);
      if (prependItem)
      this.unshift(prependItem);
      return this;



      And below is added to the SharePoint page so Google Charts can be loaded:



      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"></script>
      <script type = "text/javascript">
      google.charts.load('current', packages: ['corechart']);
      </script>






      javascript beginner formatting





      share







      New contributor




      KGlasier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share







      New contributor




      KGlasier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share






      New contributor




      KGlasier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 7 mins ago









      KGlasierKGlasier

      1012




      1012




      New contributor




      KGlasier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      KGlasier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      KGlasier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          KGlasier is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216294%2fextract-and-manipulate-date-from-sharepoint-and-export-into-google-charts%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          KGlasier is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          KGlasier is a new contributor. Be nice, and check out our Code of Conduct.












          KGlasier is a new contributor. Be nice, and check out our Code of Conduct.











          KGlasier is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216294%2fextract-and-manipulate-date-from-sharepoint-and-export-into-google-charts%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          बाताम इन्हें भी देखें सन्दर्भ दिक्चालन सूची1°05′00″N 104°02′0″E / 1.08333°N 104.03333°E / 1.08333; 104.033331°05′00″N 104°02′0″E / 1.08333°N 104.03333°E / 1.08333; 104.03333

          Why is the 'in' operator throwing an error with a string literal instead of logging false?Why can't I use switch statement on a String?Python join: why is it string.join(list) instead of list.join(string)?Multiline String Literal in C#Why does comparing strings using either '==' or 'is' sometimes produce a different result?How to initialize an array's length in javascript?How can I print literal curly-brace characters in python string and also use .format on it?Why does ++[[]][+[]]+[+[]] return the string “10”?Why is char[] preferred over String for passwords?Why does this code using random strings print “hello world”?jQuery.inArray(), how to use it right?

          How can we generalize the fact of finite dimensional vector space to an infinte dimensional case?$k[x]$-module and cyclic module over a finite dimensional vector spaceSubspace of a finite dimensional space is finite dimensionalIf V is an infinite-dimensional vector space, and S is an infinite-dimensional subspace of V, must the dimension of V/S be finite? ExplainWhy is an infinite dimensional space so different than a finite dimensional one?base for finite dimensional vector space is not infinite dimensional vector space?Any finite-dimensional vector space is the dual space of anotherHaving Trouble Understanding Meaning Of A Finite-Dimensional Vector SpaceProve that “Every subspaces of a finite-dimensional vector space is finite-dimensional”Ring as a finite dimensional Vector space over a field KQuestion regarding basis and dimension