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

How could Frankenstein get the parts for his _second_ creature?

What is the opposite of 'gravitas'?

How can I get through very long and very dry, but also very useful technical documents when learing a new tool?

What defines a dissertation?

Can I Retrieve Email Addresses from BCC?

Is there a problem with hiding "forgot password" until it's needed?

Go Pregnant or Go Home

The Riley Riddle Mine

What's the purpose of "true" in bash "if sudo true; then"

What is the oldest known work of fiction?

Mapping a list into a phase plot

Lay out the Carpet

Time travel short story where a man arrives in the late 19th century in a time machine and then sends the machine back into the past

At which point does a character regain all their Hit Dice?

Increase performance creating Mandelbrot set in python

How can a jailer prevent the Forge Cleric's Artisan's Blessing from being used?

How does it work when somebody invests in my business?

Trouble understanding overseas colleagues

What to do with wrong results in talks?

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

What are the ramifications of creating a homebrew world without an Astral Plane?

Failed to fetch jessie backports repository

What would happen if the UK refused to take part in EU Parliamentary elections?

How to be diplomatic in refusing to write code that breaches the privacy of our users



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|improve this question







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|improve this question







    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|improve this question







      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|improve this question







      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|improve this question







      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|improve this question




      share|improve this question






      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 11 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

          名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

          Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

          Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar