Advertisement
stevekamau

Untitled

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