Advertisement
stevekamau

Untitled

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