Advertisement
stevekamau

Untitled

Oct 28th, 2016
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 55.00 KB | None | 0 0
  1. package com.duka.activities;
  2.  
  3. import android.app.Activity;
  4. import android.content.Context;
  5. import android.graphics.Color;
  6. import android.net.ConnectivityManager;
  7. import android.net.NetworkInfo;
  8. import android.os.AsyncTask;
  9. import android.os.Bundle;
  10. import android.support.v7.app.AppCompatActivity;
  11. import android.support.v7.widget.Toolbar;
  12. import android.util.Log;
  13. import android.view.MenuItem;
  14. import android.view.View;
  15. import android.widget.AdapterView;
  16. import android.widget.ArrayAdapter;
  17. import android.widget.RadioButton;
  18. import android.widget.RelativeLayout;
  19. import android.widget.Spinner;
  20. import android.widget.TextView;
  21.  
  22. import com.duka.R;
  23. import com.github.mikephil.charting.charts.LineChart;
  24. import com.github.mikephil.charting.charts.PieChart;
  25. import com.github.mikephil.charting.components.Legend;
  26. import com.github.mikephil.charting.components.XAxis;
  27. import com.github.mikephil.charting.data.Entry;
  28. import com.github.mikephil.charting.data.LineData;
  29. import com.github.mikephil.charting.data.LineDataSet;
  30. import com.github.mikephil.charting.data.PieData;
  31. import com.github.mikephil.charting.data.PieDataSet;
  32. import com.github.mikephil.charting.highlight.Highlight;
  33. import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
  34. import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
  35. import com.github.mikephil.charting.utils.ColorTemplate;
  36. import com.loopj.android.http.AsyncHttpClient;
  37. import com.loopj.android.http.AsyncHttpResponseHandler;
  38. import com.loopj.android.http.RequestParams;
  39.  
  40. import org.json.JSONArray;
  41. import org.json.JSONException;
  42. import org.json.JSONObject;
  43.  
  44. import java.text.DateFormat;
  45. import java.text.DecimalFormat;
  46. import java.text.ParseException;
  47. import java.text.SimpleDateFormat;
  48. import java.util.ArrayList;
  49. import java.util.Arrays;
  50. import java.util.Calendar;
  51. import java.util.Collections;
  52. import java.util.Comparator;
  53. import java.util.Date;
  54. import java.util.HashMap;
  55. import java.util.List;
  56. import java.util.Locale;
  57.  
  58. import butterknife.BindView;
  59. import butterknife.ButterKnife;
  60. import cz.msebera.android.httpclient.Header;
  61. import dataBaseHandlers.SalesHandler;
  62. import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
  63. import utility.AccountSharedPreferences;
  64. import utility.Crouton;
  65. import utility.CustomMarkerView;
  66. import utility.CustomValueFormatter;
  67. import utility.PercentagesValueFormatter;
  68. import utility.PeriodHelper;
  69. import utility.Style;
  70.  
  71. public class Reports extends AppCompatActivity {
  72.     SalesHandler sh;
  73.     @BindView(R.id.app_bar)
  74.     Toolbar toolbar;
  75.     @BindView(R.id.hour_radioBtn)
  76.     RadioButton hourButton;
  77.     @BindView(R.id.day_radioBtn)
  78.     RadioButton dayButton;
  79.     @BindView(R.id.month_radioBtn)
  80.     RadioButton monthButton;
  81.     @BindView(R.id.for_1)
  82.     Spinner year_spinner;
  83.     @BindView(R.id.for_2)
  84.     Spinner day_spinner;
  85.     @BindView(R.id.for_3)
  86.     Spinner month_spinner;
  87.     @BindView(R.id.spinner_lay1)
  88.     RelativeLayout layout1;
  89.     @BindView(R.id.spinner_lay2)
  90.     RelativeLayout layout2;
  91.     @BindView(R.id.spinner_lay3)
  92.     RelativeLayout layout3;
  93.     @BindView(R.id.prog1)
  94.     SmoothProgressBar progressBar;
  95.     @BindView(R.id.expenses_line_graph)
  96.     LineChart expensesLineChart;
  97.     @BindView(R.id.linegraph)
  98.     LineChart salesLineChart;
  99.     @BindView(R.id.x_title)
  100.     TextView salesXTitle;
  101.     @BindView(R.id.tvContent)
  102.     TextView tvContent;
  103.     @BindView(R.id.tv_products_data)
  104.     TextView tvProductsData;
  105.     @BindView(R.id.sales_y_axis)
  106.     TextView tvSalesYAaxis;
  107.     @BindView(R.id.sales_totals)
  108.     TextView tvSalesTotals;
  109.     @BindView(R.id.products_totals)
  110.     TextView tvProductsTotals;
  111.     @BindView(R.id.cust_totals)
  112.     TextView tvCustomerTotals;
  113.     @BindView(R.id.staff_totals)
  114.     TextView tvStaffTotals;
  115.     @BindView(R.id.product_pie_chart)
  116.     PieChart product_pieChart;
  117.     @BindView(R.id.customer_pie_chart)
  118.     PieChart customer_pieChart;
  119.     @BindView(R.id.staff_pie_chart)
  120.     PieChart staff_pieChart;
  121.     @BindView(R.id.quantities_radioBtn)
  122.     RadioButton quantitiesButton;
  123.     @BindView(R.id.price_radioBtn)
  124.     RadioButton priceButton;
  125.     String date, final_month;
  126.     int yearCheck = 0;
  127.     int monthCheck = 0;
  128.     int dayCheck = 0;
  129.     int piechartCheck = 0;
  130.     AccountSharedPreferences asp;
  131.     String[] day_spinner_array;
  132.     String[] month_spinner_array;
  133.     Boolean isYear = true;
  134.     Boolean isDay = true;
  135.     Boolean isMonth = true;
  136.     PeriodHelper monthPosition;
  137.     AsyncHttpClient client;
  138.     String variant, period_label;
  139.     JSONArray salesArray;
  140.     Legend l;
  141.  
  142.     public static JSONArray getSortedListByDate(JSONArray array) throws JSONException {
  143.         List<JSONObject> list = new ArrayList<JSONObject>();
  144.         for (int i = 0; i < array.length(); i++) {
  145.             list.add(0, array.getJSONObject(i));
  146.         }
  147.         Collections.sort(list, new SortBasedOnCreatedAt());
  148.  
  149.         JSONArray resultArray = new JSONArray(list);
  150.  
  151.         return resultArray;
  152.     }
  153.  
  154.     @Override
  155.     protected void onCreate(Bundle savedInstanceState) {
  156.         super.onCreate(savedInstanceState);
  157.         setContentView(R.layout.activity_reports);
  158.         ButterKnife.bind(this);
  159.  
  160.         setSupportActionBar(toolbar);
  161.         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  162.         getSupportActionBar().setTitle("Reports");
  163.         toolbar.setNavigationIcon(com.duka.R.drawable.menu);
  164.         sh = new SalesHandler(getApplicationContext());
  165.         sh.deletePreviousDaySales();
  166. //        sh.getSumOfGroupedTime();
  167.         asp = new AccountSharedPreferences(this);
  168.         monthPosition = new PeriodHelper();
  169.         client = new AsyncHttpClient();
  170.         variant = "price";
  171.         sh.setVariant(variant);
  172.         createViews();
  173.  
  174.     }
  175.  
  176.     private void createViews() {
  177.         setUpSpinners();
  178.         //set sales y axis label
  179.         tvSalesYAaxis.setText("TOTAL PRICES");
  180.         initializeSalesMPChart(sh.sales_values(), sh.hour_labels(), "hours");
  181.         initializeProductPieChart(sh.products_values(), sh.product_labels());
  182.         initializeCustomerPieChart(sh.customer_values(), sh.customer_labels());
  183.         initializeStaffPieChart(sh.staff_values(), sh.staff_labels());
  184.  
  185.         //display totals
  186.         displayTotalAmount();
  187.         //check for connectivity
  188.         ConnectivityManager cm =
  189.                 (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  190.         NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
  191.         boolean isConnected = activeNetwork != null &&
  192.                 activeNetwork.isConnectedOrConnecting();
  193.         if (isConnected) {
  194.             date = year_spinner.getSelectedItem() + "/"
  195.                     + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
  196.                     + day_spinner.getSelectedItem();
  197.             getDataFrom(date, "hours");
  198.         } else {
  199.             Crouton.makeText(Reports.this, "Check your network connection",
  200.                     Style.ALERT, com.duka.R.id.report_holder).show();
  201.         }
  202.  
  203. //        initializeExpensesMPChart(sh.values(), sh.hour_labels());
  204.     }
  205.  
  206.     private void initializeSalesMPChart(ArrayList<Entry> values, ArrayList<String> labels, String period) {
  207.  
  208.         Log.d("report_api_", "api_request displaying in chart");
  209.         CustomMarkerView mv = new CustomMarkerView(this, getApplicationContext(),
  210.                 R.layout.custom_marker_view_layout, "sales", labels, period, variant);
  211.         // set the marker to the chart
  212.         salesLineChart.setMarkerView(mv);
  213. //        mpChart.setOnChartGestureListener(this);
  214. //        mpChart.setOnChartValueSelectedListener(this);
  215.         // ArrayList<Entry> values = new ArrayList<>();
  216.  
  217.         //x,y
  218.        /* values.add(new Entry(5, 10));
  219.         values.add(new Entry(2, 4));
  220.         values.add(new Entry(6, 10));
  221.         values.add(new Entry(3, 1));
  222.         values.add(new Entry(6, 10));
  223.         values.add(new Entry(7, 13));
  224.         values.add(new Entry(9, 7));*/
  225.  
  226.         LineDataSet report = new LineDataSet(values, "Records");
  227.         /*report.setAxisDependency(YAxis.AxisDependency.LEFT);
  228.         report.setColor(getResources().getColor(R.color.green_color));
  229.         report.setCircleColor(Color.RED);
  230.         report.setCircleColorHole(Color.RED);
  231.         report.setCircleRadius(2f);
  232.         report.setHighLightColor(Color.parseColor("#448AFF"));*/
  233.         report.setColor(getResources().getColor(R.color.colorPrimary));
  234. //        report.setColor(Color.parseColor("#758cbb"));
  235. //        report.setColor(getResources().getColor(R.color.green_color));
  236. //        report.setCircleColor(Color.BLACK);
  237.         report.setCircleColor(Color.parseColor("#ffc755"));
  238.         report.setLineWidth(3f);
  239.         report.setCircleSize(3f);
  240. //        report.setFillAlpha(10);
  241.         report.setFillColor(Color.parseColor("#2d374c"));
  242. //        report.setDrawCircles(true);
  243. //        report.setValueTextSize(-5f);
  244.         report.setValueTextSize(0f);
  245.  
  246.         ArrayList<ILineDataSet> dataSets = new ArrayList<>();
  247.         dataSets.add(report);
  248.  
  249.         LineData data = new LineData(labels, dataSets);
  250.         data.setValueFormatter(new CustomValueFormatter());
  251.         XAxis xAxis = salesLineChart.getXAxis();
  252.         xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
  253.         xAxis.setTextSize(10f);
  254.         xAxis.setDrawAxisLine(true);
  255.         xAxis.setDrawGridLines(false);
  256.         xAxis.setTextSize(9);
  257. //        if (period.equals("hours")) {
  258. //
  259. //        }
  260. //        if (period.equals("days")) {
  261. //            xAxis.setLabelsToSkip(1);
  262. //        }
  263. //        if (period.equals("months")) {
  264. //
  265. //        }
  266.  
  267.  
  268.         Legend l = salesLineChart.getLegend();
  269.         l.setEnabled(false);
  270.         //indicates if auto scaling on the y axis is enabled
  271.         // salesLineChart.setAutoScaleMinMaxEnabled(true);
  272.         salesLineChart.setDescription("");
  273.         // if disabled, scaling can be done on x- and y-axis separately
  274.         salesLineChart.setPinchZoom(true);
  275.         salesLineChart.setDrawBorders(false);
  276.         /*
  277.         salesLineChart.setVisibleXRangeMinimum(4);*/
  278.         salesLineChart.setBorderColor(getResources().getColor(R.color.grey_medium));
  279.         salesLineChart.setScaleEnabled(true);
  280.         salesLineChart.setTouchEnabled(true);
  281.         salesLineChart.setDragEnabled(true);
  282.         salesLineChart.setDoubleTapToZoomEnabled(false);
  283.         salesLineChart.getAxisLeft().setEnabled(true);
  284.         salesLineChart.getAxisLeft().setTextColor(getResources().getColor(R.color.grey_medium));
  285.         salesLineChart.getAxisRight().setEnabled(false);
  286.         salesLineChart.getXAxis().setEnabled(true);
  287.         salesLineChart.getAxisLeft().setAxisLineColor(getResources().getColor(R.color.grey_medium));
  288.         salesLineChart.getAxisLeft().setGridColor(getResources().getColor(R.color.grey_medium));
  289.         salesLineChart.getXAxis().setAxisLineColor(getResources().getColor(R.color.grey_medium));
  290.         salesLineChart.getXAxis().setGridColor(getResources().getColor(R.color.grey_medium));
  291.         salesLineChart.getXAxis().setTextColor(getResources().getColor(R.color.grey_medium));
  292.         salesLineChart.animateXY(2000, 2000);
  293.         salesLineChart.setNoDataTextDescription("No data available");
  294.         //salesLineChart.invalidate();
  295.         salesLineChart.notifyDataSetChanged();
  296.  
  297.         salesLineChart.invalidate();
  298.  
  299.         salesLineChart.setData(data);
  300.  
  301.         Log.d("array_report", "done setting sales to graph");
  302.     }
  303.  
  304.     private void initializeProductPieChart(ArrayList<Entry> p_entries, final ArrayList<String> product_names) {
  305.        /* ArrayList<Entry> entries = new ArrayList<>();
  306.         entries.add(new Entry(4f, 0));
  307.         entries.add(new Entry(8f, 1));
  308.         entries.add(new Entry(6f, 2));
  309.         entries.add(new Entry(12f, 3));
  310.         entries.add(new Entry(18f, 4));
  311.         entries.add(new Entry(9f, 5));*/
  312.  
  313.         PieDataSet dataset = new PieDataSet(p_entries, "");
  314.  
  315.       /*  ArrayList<String> labels = new ArrayList<String>();
  316.         labels.add("January");
  317.         labels.add("February");
  318.         labels.add("March");
  319.         labels.add("April");
  320.         labels.add("May");
  321.         labels.add("June");*/
  322.         l = product_pieChart.getLegend();
  323.         product_pieChart.getLegend().setWordWrapEnabled(true);
  324.         l.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT);
  325.         l.setXEntrySpace(15f);
  326.         l.setYEntrySpace(0f);
  327.         l.setYOffset(0f);
  328.  
  329.         Log.d("legend_", Arrays.toString(l.getColors()) + "/" + Arrays.toString(l.getLabels()));
  330.  
  331.         PieData data = new PieData(product_names, dataset);
  332.  
  333.         // add a lot of colors
  334.         ArrayList<Integer> colors = new ArrayList<Integer>();
  335.  
  336.         for (int c : ColorTemplate.VORDIPLOM_COLORS)
  337.             colors.add(c);
  338.         for (int c : ColorTemplate.PASTEL_COLORS)
  339.             colors.add(c);
  340.         for (int c : ColorTemplate.COLORFUL_COLORS)
  341.             colors.add(c);
  342.         for (int c : ColorTemplate.JOYFUL_COLORS)
  343.             colors.add(c);
  344.         for (int c : ColorTemplate.LIBERTY_COLORS)
  345.             colors.add(c);
  346.  
  347.         colors.add(ColorTemplate.getHoloBlue());
  348.  
  349.         dataset.setColors(colors);
  350. //        data.setValueTextSize(0);
  351. //        dataset.setColors(getResources().getIntArray(R.array.androidcolors));
  352.         dataset.setSliceSpace(0);
  353.         data.setValueFormatter(new PercentagesValueFormatter());
  354.         product_pieChart.setDragDecelerationFrictionCoef(0.95f);
  355.         product_pieChart.setDescription("");
  356.         product_pieChart.setUsePercentValues(true);
  357.         product_pieChart.setData(data);
  358.         product_pieChart.animateY(2000);
  359.         product_pieChart.setDescriptionTextSize(0);
  360.         product_pieChart.setDrawSliceText(false);
  361.         product_pieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
  362.             @Override
  363.             public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
  364.                 Log.d("chart_data", e.getXIndex() + "/" + product_names.get(e.getXIndex()));
  365. //                piechartCheck = piechartCheck + 1;
  366. //                if (piechartCheck > 1) {
  367.                 tvProductsData.setVisibility(View.VISIBLE);
  368.                 if (variant.equals("price")) {
  369.                     tvProductsData.setText(product_names.get(e.getXIndex()));
  370.                 } else {
  371.                     tvProductsData.setText(product_names.get(e.getXIndex()));
  372.                 }
  373. //                }
  374.             }
  375.  
  376.             @Override
  377.             public void onNothingSelected() {
  378.  
  379.             }
  380.         });
  381.  
  382.     }
  383.  
  384.     private void initializeCustomerPieChart(ArrayList<Entry> c_entries, ArrayList<String> customer_names) {
  385.         PieDataSet dataset = new PieDataSet(c_entries, "");
  386.  
  387.       /*  ArrayList<String> labels = new ArrayList<String>();
  388.         labels.add("January");
  389.         labels.add("February");
  390.         labels.add("March");
  391.         labels.add("April");
  392.         labels.add("May");
  393.         labels.add("June");*/
  394.         Legend l = customer_pieChart.getLegend();
  395.         customer_pieChart.getLegend().setWordWrapEnabled(true);
  396.         l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
  397.         l.setXEntrySpace(7f);
  398.         l.setYEntrySpace(0f);
  399.         l.setYOffset(0f);
  400.  
  401.         PieData data = new PieData(customer_names, dataset);
  402.         // add a lot of colors
  403.         ArrayList<Integer> colors = new ArrayList<Integer>();
  404.  
  405.         for (int c : ColorTemplate.VORDIPLOM_COLORS)
  406.             colors.add(c);
  407.         for (int c : ColorTemplate.PASTEL_COLORS)
  408.             colors.add(c);
  409.         for (int c : ColorTemplate.COLORFUL_COLORS)
  410.             colors.add(c);
  411.         for (int c : ColorTemplate.JOYFUL_COLORS)
  412.             colors.add(c);
  413.         for (int c : ColorTemplate.LIBERTY_COLORS)
  414.             colors.add(c);
  415.  
  416.         colors.add(ColorTemplate.getHoloBlue());
  417.  
  418.         colors.add(ColorTemplate.getHoloBlue());
  419.  
  420.         data.setValueFormatter(new PercentagesValueFormatter());
  421.         dataset.setColors(colors);
  422. //        dataset.setColors(getResources().getIntArray(R.array.androidcolors));
  423. //        dataset.setColors(ColorTemplate.COLORFUL_COLORS); //
  424.         customer_pieChart.setDescription("");
  425.         customer_pieChart.setDragDecelerationFrictionCoef(0.95f);
  426.         customer_pieChart.setDescription("");
  427.         customer_pieChart.setUsePercentValues(true);
  428.         customer_pieChart.setData(data);
  429.         customer_pieChart.setDescriptionTextSize(0);
  430.         customer_pieChart.setDrawSliceText(false);
  431.         customer_pieChart.animateY(2000);
  432.     }
  433.  
  434.     private void initializeStaffPieChart(ArrayList<Entry> entries, ArrayList<String> staff_names) {
  435.         PieDataSet dataset = new PieDataSet(entries, "");
  436.         Legend l = staff_pieChart.getLegend();
  437.         staff_pieChart.getLegend().setWordWrapEnabled(true);
  438.         l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
  439.         l.setXEntrySpace(7f);
  440.         l.setYEntrySpace(0f);
  441.         l.setYOffset(0f);
  442.  
  443.         PieData data = new PieData(staff_names, dataset);
  444.         // add a lot of colors
  445.         ArrayList<Integer> colors = new ArrayList<Integer>();
  446.  
  447.         for (int c : ColorTemplate.VORDIPLOM_COLORS)
  448.             colors.add(c);
  449.         for (int c : ColorTemplate.PASTEL_COLORS)
  450.             colors.add(c);
  451.         for (int c : ColorTemplate.COLORFUL_COLORS)
  452.             colors.add(c);
  453.         for (int c : ColorTemplate.JOYFUL_COLORS)
  454.             colors.add(c);
  455.         for (int c : ColorTemplate.LIBERTY_COLORS)
  456.             colors.add(c);
  457.  
  458.         colors.add(ColorTemplate.getHoloBlue());
  459.  
  460.         colors.add(ColorTemplate.getHoloBlue());
  461.  
  462.         data.setValueFormatter(new PercentagesValueFormatter());
  463.         dataset.setColors(colors);
  464. //        dataset.setColors(getResources().getIntArray(R.array.androidcolors));
  465. //        dataset.setColors(ColorTemplate.COLORFUL_COLORS); //
  466.         staff_pieChart.setDescription("");
  467.         staff_pieChart.setDragDecelerationFrictionCoef(0.95f);
  468.         staff_pieChart.setDescription("");
  469.         staff_pieChart.setUsePercentValues(true);
  470.         staff_pieChart.setData(data);
  471.         staff_pieChart.setDescriptionTextSize(0);
  472.         staff_pieChart.setDrawSliceText(false);
  473.         staff_pieChart.animateY(2000);
  474.     }
  475.  
  476.     private void setUpSpinners() {
  477.         //for year spinner
  478.         yearSpinner();
  479.         //for month spinner
  480.         monthSpinner();
  481.         //for day spinner
  482.         daySpinner(true);
  483.  
  484.     }
  485.  
  486.     public void setCustomLegend() {
  487.  
  488.     }
  489.  
  490.     private void yearSpinner() {
  491.         List<String> year_spinner_array = new ArrayList<>();
  492.         Calendar c3 = Calendar.getInstance();
  493.         c3.add(Calendar.MONTH, -1);
  494.         c3.add(Calendar.DAY_OF_MONTH, -1);
  495.         SimpleDateFormat mFormat3 = new SimpleDateFormat("yyyy", Locale.US);
  496.         int year = Integer.parseInt(mFormat3.format(c3.getTime()));
  497.         year_spinner_array.add(0, String.valueOf(year - 4));
  498.         year_spinner_array.add(0, String.valueOf(year - 3));
  499.         year_spinner_array.add(0, String.valueOf(year - 2));
  500.         year_spinner_array.add(0, String.valueOf(year - 1));
  501.         year_spinner_array.add(0, String.valueOf(year));
  502.  
  503.         ArrayAdapter<String> spinnerArrayAdapter3 = new ArrayAdapter<String>(this,
  504.                 R.layout.period_spinner_item, year_spinner_array);
  505.         //selected item will look like a spinner set from XML
  506.         spinnerArrayAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  507.         year_spinner.setAdapter(spinnerArrayAdapter3);
  508.         year_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  509.             @Override
  510.             public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
  511.                 yearCheck = yearCheck + 1;
  512.                 if (yearCheck > 1) {
  513. //                    date = (String) adapterView.getItemAtPosition(i);
  514.                     if (isMonth && isYear) {
  515.                         if (isDay) {
  516.                             date = year_spinner.getSelectedItem() + "/"
  517.                                     + month_spinner.getItemAtPosition(i) + "/"
  518.                                     + day_spinner.getSelectedItem();
  519.                             getDataFrom(date, "months");
  520. //                            Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
  521.                         } else {
  522.                             date = (String) adapterView.getItemAtPosition(i) + "/"
  523.                                     + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem());
  524.                             getDataFrom(date, "months");
  525. //                            Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
  526.                         }
  527.  
  528.                     } else {
  529.                         date = (String) adapterView.getItemAtPosition(i);
  530.                         getDataFrom(date, "months");
  531. //                        Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
  532.                     }
  533.                 }
  534.  
  535.             }
  536.  
  537.             @Override
  538.             public void onNothingSelected(AdapterView<?> adapterView) {
  539.  
  540.             }
  541.         });
  542.     }
  543.  
  544.     private void monthSpinner() {
  545.        /* List<String> month_spinner_array = new ArrayList<>();
  546.         Calendar c2 = Calendar.getInstance();
  547.         c2.add(Calendar.MONTH, -1);
  548.         c2.add(Calendar.DAY_OF_MONTH, -1);
  549.         SimpleDateFormat mFormat2 = new SimpleDateFormat("MM", Locale.US);
  550.         while (c2.before(Calendar.getInstance())) {
  551.             month_spinner_array.add(0, mFormat2.format(c2.getTime()));
  552.             c2.add(Calendar.DAY_OF_MONTH, 1);
  553.         }
  554. */
  555.         Calendar c2 = Calendar.getInstance();
  556.         c2.add(Calendar.MONTH, 0);
  557.         c2.add(Calendar.DAY_OF_MONTH, 0);
  558.         SimpleDateFormat mFormat2 = new SimpleDateFormat("MMMM", Locale.US);
  559.         String month = mFormat2.format(c2.getTime());
  560.  
  561.         if (month.startsWith("0")) {
  562.             final_month = mFormat2.format(c2.getTime()).replace("0", "");
  563.         } else {
  564.             final_month = mFormat2.format(c2.getTime());
  565.         }
  566.  
  567.         month_spinner_array = getResources().getStringArray(R.array.month_name_arrays);
  568.         ArrayAdapter<String> spinnerArrayAdapter2 = new ArrayAdapter<String>(this,
  569.                 R.layout.period_spinner_item, month_spinner_array);
  570.         //selected item will look like a spinner set from XML
  571.         spinnerArrayAdapter2.setDropDownViewResource(R.layout.period_spinner_dropdown_item);
  572.         month_spinner.setAdapter(spinnerArrayAdapter2);
  573.         month_spinner.setSelection(((ArrayAdapter) month_spinner.getAdapter()).getPosition(month));
  574.         month_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  575.             @Override
  576.             public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
  577.                 monthCheck = monthCheck + 1;
  578.                 if (monthCheck > 1) {
  579. //                    date = (String) adapterView.getItemAtPosition(i);
  580. //                    daySpinner(false);
  581.                     if (isMonth && isYear) {
  582.                         if (isDay) {
  583.                             date = year_spinner.getSelectedItem() + "/"
  584.                                     + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
  585.                                     + day_spinner.getSelectedItem();
  586.                             getDataFrom(date, "days");
  587. //                            Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
  588.                         } else {
  589.                             date = year_spinner.getSelectedItem() + "/"
  590.                                     + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem());
  591.                             getDataFrom(date, "days");
  592. //                            Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
  593.                         }
  594.  
  595.                     }
  596.  
  597.                 }
  598.             }
  599.  
  600.             @Override
  601.             public void onNothingSelected(AdapterView<?> adapterView) {
  602.  
  603.             }
  604.         });
  605.     }
  606.  
  607.     private void daySpinner(final boolean b) {
  608.  
  609.         Calendar c = Calendar.getInstance();
  610.         c.add(Calendar.MONTH, -1);
  611.         c.add(Calendar.DAY_OF_MONTH, 0);
  612.         SimpleDateFormat mFormat = new SimpleDateFormat("dd", Locale.US);
  613. //        while (c.before(Calendar.getInstance())) {
  614. ////            day_spinner_array.add(0, mFormat.format(c.getTime()));
  615. //            c.add(Calendar.DAY_OF_MONTH, 1);
  616. //        }
  617.         String today = mFormat.format(c.getTime());
  618.  
  619. //        if () {
  620. //            day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
  621. //        }
  622.  
  623.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("1")) {
  624.             day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
  625.         }
  626.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("2")) {
  627.             day_spinner_array = getResources().getStringArray(R.array.days_28_arrays);
  628.         }
  629.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("3")) {
  630.             day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
  631.         }
  632.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("4")) {
  633.             day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
  634.         }
  635.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("5")) {
  636.             day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
  637.         }
  638.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("6")) {
  639.             day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
  640.         }
  641.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("7")) {
  642.             day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
  643.         }
  644.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("8")) {
  645.             day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
  646.         }
  647.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("9")) {
  648.             day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
  649.         }
  650.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("10")) {
  651.             day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
  652.         }
  653.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("11")) {
  654.             day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
  655.         }
  656.         if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("12")) {
  657.             day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
  658.         }
  659.  
  660.         Log.d("month_position", monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()));
  661. //        day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
  662.         ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,
  663.                 R.layout.period_spinner_item, day_spinner_array);
  664. //
  665. //        //selected item will look like a spinner set from XML
  666.         spinnerArrayAdapter.setDropDownViewResource(R.layout.period_spinner_dropdown_item);
  667.         day_spinner.setAdapter(spinnerArrayAdapter);
  668.         day_spinner.setSelection(((ArrayAdapter) day_spinner.getAdapter()).getPosition(today));
  669.  
  670.         day_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  671.             @Override
  672.             public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
  673.                 if (b) {
  674.                     dayCheck = dayCheck + 1;
  675.                     if (dayCheck > 1) {
  676.                         date = year_spinner.getSelectedItem() + "/"
  677.                                 + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
  678.                                 + (String) adapterView.getItemAtPosition(i);
  679.                         getDataFrom(date, "hours");
  680. //                        Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
  681.                     }
  682.                 }
  683.             }
  684.  
  685.             @Override
  686.             public void onNothingSelected(AdapterView<?> adapterView) {
  687.  
  688.             }
  689.         });
  690.     }
  691.  
  692.     private void displayTotalAmount() {
  693.         DecimalFormat priceFormat = new DecimalFormat("###,###,###.00");
  694.         DecimalFormat quantityFormat = new DecimalFormat("###,###,###");
  695.         String total = "";
  696.         if (variant.equals("price")) {
  697.             total = String.valueOf(priceFormat.format(sh.getTotalSales()));
  698.             if (total.equals(".00")) {
  699.                 tvSalesTotals.setText(asp.getCurrency() + " " + "0.00");
  700.                 tvProductsTotals.setText(asp.getCurrency() + " " + "0.00");
  701.                 tvCustomerTotals.setText(asp.getCurrency() + " " + "0.00");
  702.                 tvStaffTotals.setText(asp.getCurrency() + " " + "0.00");
  703.             } else {
  704.                 tvSalesTotals.setText(asp.getCurrency() + " " + total);
  705.                 tvProductsTotals.setText(asp.getCurrency() + " " + total);
  706.                 tvCustomerTotals.setText(asp.getCurrency() + " " + total);
  707.                 tvStaffTotals.setText(asp.getCurrency() + " " + total);
  708.             }
  709.         } else {
  710.             total = String.valueOf(quantityFormat.format(Double.valueOf(sh.getTotalQuantityOfProducts())));
  711.             tvSalesTotals.setText(total + " Products");
  712.             tvProductsTotals.setText(total + " Products");
  713.             tvCustomerTotals.setText(total + " Products");
  714.             tvStaffTotals.setText(total + " Products");
  715.         }
  716.     }
  717.  
  718.     private void getDataFrom(String period, final String label) {
  719.         Log.d("report_api_", "api_request made");
  720.         client.cancelAllRequests(true);
  721.         client.cancelRequests(getApplicationContext(), true);
  722.         ConnectivityManager cm =
  723.                 (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  724.  
  725.         NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
  726.         boolean isConnected = activeNetwork != null &&
  727.                 activeNetwork.isConnectedOrConnecting();
  728.         if (isConnected) {
  729.             String url = getResources().getString(R.string.url) + "sales/" + period
  730.                     + "/api";
  731.             RequestParams params = new RequestParams();
  732.             client.addHeader("class", "Business");
  733.             client.addHeader("attendant_name", asp.getAttendantName());
  734.             client.addHeader("attendant_id", asp.getAttendantId());
  735.             client.addHeader(getResources().getString(R.string.api_token), asp.getApiKey());
  736.             client.get(url,
  737.                     params, new AsyncHttpResponseHandler() {
  738.                         @Override
  739.                         public void onStart() {
  740.  
  741.                             Log.d("report_api_", "api_request started");
  742.                             progressBar.setVisibility(View.VISIBLE);
  743.                         }
  744.  
  745.                         @Override
  746.                         public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
  747.                             String s = new String(responseBody);
  748.                             progressBar.setVisibility(View.INVISIBLE);
  749.                             Log.d("sale_reports_", s);
  750.                             try {
  751.                                 Log.d("report_api_", "api_request successful");
  752.                                 JSONObject objs = new JSONObject(s);
  753.                                 HashMap<String, String> map = new HashMap<String, String>();
  754.  
  755.                                 Boolean success = objs.getBoolean("success");
  756.                                 if (success) {
  757.                                     period_label = label;
  758.                                     salesArray = objs.getJSONArray("data");
  759.                                     sh.setLabelType(label);
  760.                                     new AsyncUpdateSalesToDisplayGraph(salesArray, label).execute();
  761.  
  762.                                 } else {
  763.                                     String failure = objs.getString("message");
  764.                                     Crouton.makeText(
  765.                                             Reports.this,
  766.                                             failure,
  767.                                             Style.ALERT, com.duka.R.id.report_holder).show();
  768.  
  769.                                 }
  770.  
  771.                             } catch (JSONException e) {
  772.  
  773.                             }
  774.                         }
  775.  
  776.                         @Override
  777.                         public void onFailure(int statusCode, Header[] headers,
  778.                                               byte[] responseBody, Throwable error) {
  779.                             progressBar.setVisibility(View.INVISIBLE);
  780.                             Log.d("something_went_wrong", String.valueOf(error));
  781.                             //errorDialog();
  782.                             Crouton.makeText(Reports.this, "Check your network connection",
  783.                                     Style.ALERT, com.duka.R.id.report_holder).show();
  784.  
  785.                         }
  786.                     }
  787.  
  788.             );
  789.         } else {
  790.             Crouton.makeText(Reports.this, "Check your network connection",
  791.                     Style.ALERT, com.duka.R.id.report_holder).show();
  792.         }
  793.     }
  794.  
  795.     public void onRadioButtonClicked(View view) {
  796.         // Is the button now checked?
  797.         boolean checked = ((RadioButton) view).isChecked();
  798.         // Check which radio button was clicked
  799.         switch (view.getId()) {
  800.             case R.id.hour_radioBtn:
  801.                 if (checked) {
  802.                     dayButton.setChecked(false);
  803.                     monthButton.setChecked(false);
  804.                     layout1.setVisibility(View.VISIBLE);
  805.                     layout2.setVisibility(View.VISIBLE);
  806.                     layout3.setVisibility(View.VISIBLE);
  807.                     isDay = true;
  808.                     isMonth = true;
  809.                     isYear = true;
  810.                     setUpRequestForPeriod("hour");
  811.                 }
  812.                 break;
  813.             case R.id.day_radioBtn:
  814.                 if (checked) {
  815.                     hourButton.setChecked(false);
  816.                     monthButton.setChecked(false);
  817.                     layout3.setVisibility(View.VISIBLE);
  818.                     layout1.setVisibility(View.VISIBLE);
  819.                     layout2.setVisibility(View.GONE);
  820.                     isDay = false;
  821.                     isMonth = true;
  822.                     isYear = true;
  823.                     setUpRequestForPeriod("days");
  824.  
  825.  
  826.                 }
  827.                 break;
  828.             case R.id.month_radioBtn:
  829.                 if (checked) {
  830.                     dayButton.setChecked(false);
  831.                     hourButton.setChecked(false);
  832.                     layout1.setVisibility(View.VISIBLE);
  833.                     layout2.setVisibility(View.GONE);
  834.                     layout3.setVisibility(View.GONE);
  835.                     isDay = false;
  836.                     isMonth = false;
  837.                     isYear = true;
  838.  
  839.                     setUpRequestForPeriod("months");
  840.                 }
  841.                 break;
  842.             case R.id.price_radioBtn:
  843.                 if (checked) {
  844.                     quantitiesButton.setChecked(false);
  845.                     variant = "price";
  846.                     sh.setVariant(variant);
  847.                     getChartDataDependingOnVariant();
  848.  
  849.                 }
  850.                 break;
  851.             case R.id.quantities_radioBtn:
  852.                 if (checked) {
  853.                     priceButton.setChecked(false);
  854.                     variant = "quantity";
  855.                     sh.setVariant(variant);
  856.                     getChartDataDependingOnVariant();
  857.                 }
  858.                 break;
  859.         }
  860.     }
  861.  
  862.     private void getChartDataDependingOnVariant() {
  863.         //if array is null, let's get data for today
  864.         try {
  865.             if (salesArray != null) {
  866.                 new AsyncUpdateSalesToDisplayGraph(salesArray, period_label).execute();
  867.             } else {
  868.                 //display totals
  869.                 displayTotalAmount();
  870.                 //start local charts
  871.                 initializeSalesMPChart(sh.sales_values(), sh.hour_labels(), "hours");
  872.                 initializeProductPieChart(sh.products_values(), sh.product_labels());
  873.                 initializeCustomerPieChart(sh.customer_values(), sh.customer_labels());
  874.                 initializeStaffPieChart(sh.staff_values(), sh.staff_labels());
  875.                 //set sales y axis label
  876.                 if (variant.equals("price")) {
  877.                     tvSalesYAaxis.setText("TOTAL PRICES");
  878.                 } else {
  879.                     tvSalesYAaxis.setText("SALES");
  880.                 }
  881.             }
  882.         } catch (JSONException e) {
  883.             e.printStackTrace();
  884.         }
  885.     }
  886.  
  887.     private void setUpRequestForPeriod(String period) {
  888.         if (period.equals("hours")) {
  889.             date = year_spinner.getSelectedItem() + "/"
  890.                     + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
  891.                     + day_spinner.getSelectedItem();
  892.         } else if (period.equals("days")) {
  893.             date = year_spinner.getSelectedItem() + "/"
  894.                     + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem());
  895.         } else {
  896.             date = year_spinner.getSelectedItem() + "";
  897.         }
  898.  
  899.         getDataFrom(date, period);
  900.     }
  901.  
  902.     @Override
  903.     public boolean onOptionsItemSelected(MenuItem item) {
  904.         // Handle action bar item clicks here. The action bar will
  905.         // automatically handle clicks on the Home/Up button, so long
  906.         // as you specify a parent activity in AndroidManifest.xml.
  907.         int id = item.getItemId();
  908.  
  909.         //noinspection SimplifiableIfStatement
  910.  
  911.         if (id == android.R.id.home) {
  912.             finish();
  913. //            MainActivity ma = new MainActivity();
  914. //            ma.openResideMenu();
  915.             return true;
  916.         }
  917.         return super.onOptionsItemSelected(item);
  918.     }
  919.  
  920.     private String getDayFormatted(String dateStr) {
  921.         DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  922.         DateFormat writeFormat = new SimpleDateFormat("dd");
  923.         Date date = null;
  924.         try {
  925.             date = readFormat.parse(dateStr);
  926.         } catch (ParseException e) {
  927.             e.printStackTrace();
  928.         }
  929.         String formattedDate = writeFormat.format(date);
  930.         return formattedDate;
  931.     }
  932.  
  933.     private String getTimeFormattedInAMPM(String dateStr) {
  934.         DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  935.         DateFormat writeFormat = new SimpleDateFormat("ha");
  936.         Date date = null;
  937.         try {
  938.             date = readFormat.parse(dateStr);
  939.         } catch (ParseException e) {
  940.             e.printStackTrace();
  941.         }
  942.         String formattedDate = writeFormat.format(date);
  943.         return formattedDate;
  944.     }
  945.  
  946.     private String getMonthFormatted(String dateStr) {
  947.         DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  948.         DateFormat writeFormat = new SimpleDateFormat("MMM ");
  949.         Date date = null;
  950.         try {
  951.             date = readFormat.parse(dateStr);
  952.         } catch (ParseException e) {
  953.             e.printStackTrace();
  954.         }
  955.         String formattedDate = writeFormat.format(date);
  956.         return formattedDate;
  957.     }
  958.  
  959.     String getCurrentDate() {
  960.         Date now = new Date();
  961.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
  962.         return sdf.format(now);
  963.     }
  964.  
  965.     private void showTotalsOnGraphs(ArrayList<String> sales_totals, ArrayList<String> product_totals, ArrayList<String> customer_totals, ArrayList<String> staff_totals) {
  966.         double sum = 0;
  967.         String unformatted_number = "";
  968.         DecimalFormat priceFormat = new DecimalFormat("###,###,###.00");
  969.         DecimalFormat quantityFormat = new DecimalFormat("###,###,###");
  970.         String total = "";
  971.         //sales totals
  972.         for (int i = 0; i < sales_totals.size(); i++) {
  973.             sum += Double.valueOf(sales_totals.get(i));
  974.         }
  975.         if (variant.equals("price")) {
  976.             total = String.valueOf(priceFormat.format(sum));
  977.             if (total.equals(".00")) {
  978.                 tvSalesTotals.setText(asp.getCurrency() + " " + "0.00");
  979.             } else {
  980.                 tvSalesTotals.setText(asp.getCurrency() + " " + total);
  981.             }
  982.         } else {
  983.             total = String.valueOf(quantityFormat.format(sum));
  984.             tvSalesTotals.setText(total + " Products");
  985.         }
  986.         //products
  987.         for (int i = 0; i < product_totals.size(); i++) {
  988.             sum += Double.valueOf(product_totals.get(i));
  989.         }
  990.         if (variant.equals("price")) {
  991.             total = String.valueOf(priceFormat.format(sum));
  992.             if (total.equals(".00")) {
  993.                 tvProductsTotals.setText(asp.getCurrency() + " " + "0.00");
  994.             } else {
  995.                 tvProductsTotals.setText(asp.getCurrency() + " " + total);
  996.             }
  997.         } else {
  998.             total = String.valueOf(quantityFormat.format(sum));
  999.             tvProductsTotals.setText(total + " Products");
  1000.         }
  1001.         //customers
  1002.         for (int i = 0; i < customer_totals.size(); i++) {
  1003.             sum += Double.valueOf(customer_totals.get(i));
  1004.         }
  1005.         if (variant.equals("price")) {
  1006.             total = String.valueOf(priceFormat.format(sum));
  1007.             if (total.equals(".00")) {
  1008.                 tvCustomerTotals.setText(asp.getCurrency() + " " + "0.00");
  1009.             } else {
  1010.                 tvCustomerTotals.setText(asp.getCurrency() + " " + total);
  1011.             }
  1012.         } else {
  1013.             total = String.valueOf(quantityFormat.format(sum));
  1014.             tvCustomerTotals.setText(total + " Products");
  1015.         }
  1016.         //staff
  1017.         for (int i = 0; i < staff_totals.size(); i++) {
  1018.             sum += Double.valueOf(staff_totals.get(i));
  1019.         }
  1020.         if (variant.equals("price")) {
  1021.             total = String.valueOf(priceFormat.format(sum));
  1022.             if (total.equals(".00")) {
  1023.                 tvStaffTotals.setText(asp.getCurrency() + " " + "0.00");
  1024.             } else {
  1025.                 tvStaffTotals.setText(asp.getCurrency() + " " + total);
  1026.             }
  1027.         } else {
  1028.             total = String.valueOf(quantityFormat.format(sum));
  1029.             tvStaffTotals.setText(total + " Products");
  1030.         }
  1031.  
  1032.     }
  1033.  
  1034.     public static class SortBasedOnCreatedAt implements Comparator<JSONObject> {
  1035.         String CompareString1 = "", CompareString2 = "";
  1036.  
  1037.         /*
  1038.         * (non-Javadoc)
  1039.         *
  1040.         * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
  1041.         * lhs- 1st message in the form of json object. rhs- 2nd message in the form
  1042.         * of json object.
  1043.         */
  1044.         @Override
  1045.         public int compare(JSONObject lhs, JSONObject rhs) {
  1046.             try {
  1047. //                return Integer.valueOf(lhs.getString("created_at")) > Integer.valueOf(rhs.getString("created_at"))
  1048. //                        ? 1 : (Integer.valueOf(lhs.getString("created_at")) < Integer.valueOf(rhs.getString("created_at")) ? -1 : 0);
  1049.  
  1050.                 CompareString1 = lhs.getString("created_at"); //Key must be present in JSON
  1051.                 CompareString2 = rhs.getString("created_at"); //Key must be present in JSON
  1052.  
  1053.             } catch (JSONException e) {
  1054.                 e.printStackTrace();
  1055.             }
  1056.             return CompareString1.compareTo(CompareString2);
  1057.  
  1058.         }
  1059.     }
  1060.  
  1061.     class AsyncUpdateSalesToDisplayGraph extends AsyncTask<Void, String, Void> {
  1062.         Activity activity;
  1063.         JSONArray sales;
  1064.         JSONObject sale_obj;
  1065.  
  1066.         ArrayList<String> sales_labels = new ArrayList<>();
  1067.         ArrayList<String> sales_totals = new ArrayList<>();
  1068.         ArrayList<Entry> sales_values = new ArrayList<>();
  1069.  
  1070.         ArrayList<String> product_names = new ArrayList<>();
  1071.         ArrayList<String> product_labelz = new ArrayList<>();
  1072.         ArrayList<String> product_totals = new ArrayList<>();
  1073.         ArrayList<Entry> product_values = new ArrayList<>();
  1074.  
  1075.         ArrayList<String> customer_names = new ArrayList<>();
  1076.         ArrayList<String> customer_labelz = new ArrayList<>();
  1077.         ArrayList<String> customer_totals = new ArrayList<>();
  1078.         ArrayList<Entry> customer_values = new ArrayList<>();
  1079.  
  1080.         ArrayList<String> staff_names = new ArrayList<>();
  1081.         ArrayList<String> staff_labelz = new ArrayList<>();
  1082.         ArrayList<String> staff_totals = new ArrayList<>();
  1083.         ArrayList<Entry> staff_values = new ArrayList<>();
  1084.         int maxLength;
  1085.  
  1086.         String label, product_label_to_truncate, customer_label_to_truncate, staff_label_to_truncate;
  1087.  
  1088.         public AsyncUpdateSalesToDisplayGraph(JSONArray sale, String label) throws JSONException {
  1089.             this.sales = getSortedListByDate(sale);
  1090.             this.label = label;
  1091.         }
  1092.  
  1093.         @Override
  1094.         protected void onPreExecute() {
  1095.             Crouton.makeText(
  1096.                     Reports.this,
  1097.                     "Processing the data...",
  1098.                     Style.INFO, com.duka.R.id.report_holder).show();
  1099.         }
  1100.  
  1101.         @Override
  1102.         protected Void doInBackground(Void... params) {
  1103.             Log.d("array_report_track", "adding sales in background");
  1104.             Log.d("array_report_track", "adding sales in background");
  1105.             JSONObject groupedSales = new JSONObject();
  1106.             JSONObject groupedProducts = new JSONObject();
  1107.             JSONObject groupedCustomers = new JSONObject();
  1108.             JSONObject groupedStaff = new JSONObject();
  1109.             JSONArray groupedSalesArray = new JSONArray();
  1110.             DecimalFormat priceFormat = new DecimalFormat("###,###,###");
  1111.             DecimalFormat quantityFormat = new DecimalFormat("###,###,###");
  1112.  
  1113.             for (int i = 0; i < sales.length(); i++) {
  1114.  
  1115.                 try {
  1116.                     sale_obj = (JSONObject) sales.get(i);
  1117.                     int id = sale_obj.getInt("id");
  1118.  
  1119.                     //update local db for today only
  1120.                     if (date.equals(getCurrentDate())) {
  1121.                         String attendant_id = sale_obj.getString("attendant_id");
  1122.                         String attendant_name = sale_obj.getString("attendant_name");
  1123.                         String business_id = sale_obj.getString("business_id");
  1124.                         String created_at = sale_obj.getString("created_at");
  1125.                         String customer_first_name = sale_obj.getString("customer_first_name");
  1126.                         String customer_id = sale_obj.getString("customer_id");
  1127.                         String customer_image = sale_obj.getString("customer_image");
  1128.                         String customer_last_name = sale_obj.getString("customer_last_name");
  1129.                         String image = sale_obj.getString("image");
  1130.                         String name = sale_obj.getString("name");
  1131.                         String price = sale_obj.getString("price");
  1132.                         String product_id = sale_obj.getString("product_id");
  1133.                         String quantity = sale_obj.getString("quantity");
  1134.                         String reader_id = sale_obj.getString("reader_id");
  1135.                         String svg = sale_obj.getString("svg");
  1136.                         String synced_at = sale_obj.getString("synced_at");
  1137.                         String time_code = sale_obj.getString("time_code");
  1138.                         String uid = sale_obj.getString("uid");
  1139.                         String updated_at = sale_obj.getString("updated_at");
  1140.                         String deleted_at = sale_obj.getString("deleted_at");
  1141.  
  1142.                         sh.updateSingleSale(String.valueOf(id), attendant_id, attendant_name,
  1143.                                 product_id, price, customer_id, customer_first_name,
  1144.                                 customer_last_name, customer_image, uid, quantity,
  1145.                                 name, image, created_at, deleted_at, svg, "false", time_code);
  1146.                     }
  1147.                     double total = sale_obj.getDouble(variant); // variant is price or quantity
  1148.  
  1149.                     // sales line graph
  1150.                     String period = ""; // hour|date|month  e.g. 9AM|31|October
  1151.                     if (label.equals("hours")) {
  1152.                         period = getTimeFormattedInAMPM(sale_obj.getString("created_at")); // hour
  1153.                     }
  1154.                     if (label.equals("days")) {
  1155.                         period = getDayFormatted(sale_obj.getString("created_at")); // date
  1156.                     }
  1157.                     if (label.equals("months")) {
  1158.                         period = getMonthFormatted(sale_obj.getString("created_at")); // month
  1159.                     }
  1160.                     int index = sales_labels.indexOf(period);
  1161.                     if (index < 0) { // doesnt exist in sales_label_1
  1162.                         sales_labels.add(period);
  1163.                         sales_values.add(new Entry((float) total, sales_labels.size() - 1));
  1164.                     } else {
  1165.                         // read the current total
  1166.                         double current_total = groupedSales.getDouble(period);
  1167.                         // increment by the sale_obj total
  1168.                         total = current_total + total;
  1169.                         sales_values.set(index, new Entry((float) total, index));
  1170.                     }
  1171.                     sales_totals.add(sale_obj.getString(variant));
  1172.                     groupedSales.put(period, total);
  1173.                     Log.d("array_report_sales", groupedSales.toString());
  1174.  
  1175.  
  1176.                     // products pie chart
  1177.                     String productName = sale_obj.getString("name");
  1178.                     index = product_names.indexOf(productName);
  1179.                     product_label_to_truncate = String.valueOf(priceFormat.format(total)) + " " + productName;
  1180.  
  1181.                     if (index < 0) {
  1182.                         // product doesnt exist in product_labelz
  1183.                         product_names.add(productName);
  1184.                         product_labelz.add(product_label_to_truncate);
  1185.                         product_values.add(new Entry((float) total, product_labelz.size() - 1));
  1186.                     } else {
  1187.                         // read the current total
  1188.                         double current_total = groupedProducts.getDouble(productName);
  1189.                         // increment by the total
  1190.                         total = current_total + total;
  1191.                         product_values.set(index, new Entry((float) total, index));
  1192.                     }
  1193.                     product_totals.add(sale_obj.getString(variant));
  1194.                     groupedProducts.put(productName, total);
  1195.                     Log.d("array_report_products", groupedProducts.toString());
  1196.  
  1197.  
  1198.                     // customers pie chart
  1199.                     String customerName = sale_obj.getString("customer_first_name") + " "
  1200.                             + sale_obj.getString("customer_last_name");
  1201.                     index = customer_names.indexOf(customerName);
  1202.                     customer_label_to_truncate = String.valueOf(quantityFormat.format(total)) + " " + customerName;
  1203.                     if (index < 0) {
  1204.                         // customer doesnt exist in customer_labelz
  1205.                         customer_names.add(customerName);
  1206.                         customer_labelz.add(customer_label_to_truncate);
  1207.                         customer_values.add(new Entry((float) total, customer_labelz.size() - 1));
  1208.                     } else {
  1209.                         // read the current total
  1210.                         double current_total = groupedCustomers.getDouble(customerName);
  1211.                         // increment by the total
  1212.                         total = current_total + total;
  1213.                         customer_values.set(index, new Entry((float) total, index));
  1214.                     }
  1215.                     customer_totals.add(sale_obj.getString(variant));
  1216.                     groupedCustomers.put(customerName, total);
  1217.                     Log.d("array_report_customer", groupedCustomers.toString());
  1218.  
  1219.  
  1220.                     // staff pie chart
  1221.                     String staffName = sale_obj.getString("attendant_name");
  1222.                     index = staff_names.indexOf(staffName);
  1223.                     staff_label_to_truncate = String.valueOf(priceFormat.format(total)) + " " + staffName;
  1224.                     if (index < 0) {
  1225.                         // staff doesnt exist in staff_labelz
  1226.                         staff_names.add(staffName);
  1227.                         staff_labelz.add(staff_label_to_truncate);
  1228.                         staff_values.add(new Entry((float) total, staff_labelz.size() - 1));
  1229.                     } else {
  1230.                         // read the current total
  1231.                         double current_total = groupedStaff.getDouble(staffName);
  1232.                         // increment by the total
  1233.                         total = current_total + total;
  1234.                         staff_values.set(index, new Entry((float) total, index));
  1235.                     }
  1236.                     staff_totals.add(sale_obj.getString(variant));
  1237.                     groupedStaff.put(staffName, total);
  1238.                     Log.d("array_report_staff", groupedStaff.toString());
  1239.  
  1240.                 } catch (JSONException e) {
  1241.                     e.printStackTrace();
  1242.                 }
  1243.  
  1244.             }
  1245.  
  1246.             Log.d("array_report_track", "done adding sales in background" + groupedSalesArray.toString());
  1247.             Log.d("array_report_sales", sales_labels.toString() + "///" + sales_values.toString());
  1248.             return null;
  1249.         }
  1250.  
  1251.         @Override
  1252.         protected void onPostExecute(Void unused) {
  1253.             //totals
  1254.             showTotalsOnGraphs(sales_totals, product_totals, customer_totals, staff_totals);
  1255.  
  1256.             Log.d("sum_sales_values", sales_values.toString() + "/" + sales_labels.toString());
  1257.             if (label.equals("hours")) {
  1258.                 salesXTitle.setText("TIME");
  1259.             }
  1260.             if (label.equals("days")) {
  1261.                 salesXTitle.setText("DATES");
  1262.             }
  1263.             if (label.equals("months")) {
  1264.                 salesXTitle.setText("MONTHS");
  1265.             }
  1266.             //set sales y axis label
  1267.             if (variant.equals("price")) {
  1268.                 tvSalesYAaxis.setText("TOTAL PRICES");
  1269.             } else {
  1270.                 tvSalesYAaxis.setText("SALES");
  1271.             }
  1272.             initializeSalesMPChart(sales_values, sales_labels, label);
  1273.             initializeProductPieChart(product_values, product_labelz);
  1274.             initializeCustomerPieChart(customer_values, customer_labelz);
  1275.             initializeStaffPieChart(staff_values, staff_labelz);
  1276.  
  1277.         }
  1278.     }
  1279. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement