Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.duka.activities;
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Color;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.support.v7.app.AppCompatActivity;
- import android.support.v7.widget.Toolbar;
- import android.util.Log;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.RadioButton;
- import android.widget.RelativeLayout;
- import android.widget.Spinner;
- import android.widget.TextView;
- import com.duka.R;
- import com.github.mikephil.charting.charts.LineChart;
- import com.github.mikephil.charting.charts.PieChart;
- import com.github.mikephil.charting.components.Legend;
- import com.github.mikephil.charting.components.XAxis;
- import com.github.mikephil.charting.data.Entry;
- import com.github.mikephil.charting.data.LineData;
- import com.github.mikephil.charting.data.LineDataSet;
- import com.github.mikephil.charting.data.PieData;
- import com.github.mikephil.charting.data.PieDataSet;
- import com.github.mikephil.charting.highlight.Highlight;
- import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
- import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
- import com.github.mikephil.charting.utils.ColorTemplate;
- import com.loopj.android.http.AsyncHttpClient;
- import com.loopj.android.http.AsyncHttpResponseHandler;
- import com.loopj.android.http.RequestParams;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.text.DateFormat;
- import java.text.DecimalFormat;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Calendar;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Locale;
- import butterknife.BindView;
- import butterknife.ButterKnife;
- import cz.msebera.android.httpclient.Header;
- import dataBaseHandlers.SalesHandler;
- import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
- import utility.AccountSharedPreferences;
- import utility.Crouton;
- import utility.CustomMarkerView;
- import utility.CustomValueFormatter;
- import utility.PercentagesValueFormatter;
- import utility.PeriodHelper;
- import utility.Style;
- public class Reports extends AppCompatActivity {
- SalesHandler sh;
- @BindView(R.id.app_bar)
- Toolbar toolbar;
- @BindView(R.id.hour_radioBtn)
- RadioButton hourButton;
- @BindView(R.id.day_radioBtn)
- RadioButton dayButton;
- @BindView(R.id.month_radioBtn)
- RadioButton monthButton;
- @BindView(R.id.for_1)
- Spinner year_spinner;
- @BindView(R.id.for_2)
- Spinner day_spinner;
- @BindView(R.id.for_3)
- Spinner month_spinner;
- @BindView(R.id.spinner_lay1)
- RelativeLayout layout1;
- @BindView(R.id.spinner_lay2)
- RelativeLayout layout2;
- @BindView(R.id.spinner_lay3)
- RelativeLayout layout3;
- @BindView(R.id.prog1)
- SmoothProgressBar progressBar;
- @BindView(R.id.expenses_line_graph)
- LineChart expensesLineChart;
- @BindView(R.id.linegraph)
- LineChart salesLineChart;
- @BindView(R.id.x_title)
- TextView salesXTitle;
- @BindView(R.id.tvContent)
- TextView tvContent;
- @BindView(R.id.tv_products_data)
- TextView tvProductsData;
- @BindView(R.id.sales_y_axis)
- TextView tvSalesYAaxis;
- @BindView(R.id.sales_totals)
- TextView tvSalesTotals;
- @BindView(R.id.products_totals)
- TextView tvProductsTotals;
- @BindView(R.id.cust_totals)
- TextView tvCustomerTotals;
- @BindView(R.id.staff_totals)
- TextView tvStaffTotals;
- @BindView(R.id.product_pie_chart)
- PieChart product_pieChart;
- @BindView(R.id.customer_pie_chart)
- PieChart customer_pieChart;
- @BindView(R.id.staff_pie_chart)
- PieChart staff_pieChart;
- @BindView(R.id.quantities_radioBtn)
- RadioButton quantitiesButton;
- @BindView(R.id.price_radioBtn)
- RadioButton priceButton;
- String date, final_month;
- int yearCheck = 0;
- int monthCheck = 0;
- int dayCheck = 0;
- int piechartCheck = 0;
- AccountSharedPreferences asp;
- String[] day_spinner_array;
- String[] month_spinner_array;
- Boolean isYear = true;
- Boolean isDay = true;
- Boolean isMonth = true;
- PeriodHelper monthPosition;
- AsyncHttpClient client;
- String variant, period_label;
- JSONArray salesArray;
- Legend l;
- public static JSONArray getSortedListByDate(JSONArray array) throws JSONException {
- List<JSONObject> list = new ArrayList<JSONObject>();
- for (int i = 0; i < array.length(); i++) {
- list.add(0, array.getJSONObject(i));
- }
- Collections.sort(list, new SortBasedOnCreatedAt());
- JSONArray resultArray = new JSONArray(list);
- return resultArray;
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_reports);
- ButterKnife.bind(this);
- setSupportActionBar(toolbar);
- getSupportActionBar().setDisplayHomeAsUpEnabled(true);
- getSupportActionBar().setTitle("Reports");
- toolbar.setNavigationIcon(com.duka.R.drawable.menu);
- sh = new SalesHandler(getApplicationContext());
- sh.deletePreviousDaySales();
- // sh.getSumOfGroupedTime();
- asp = new AccountSharedPreferences(this);
- monthPosition = new PeriodHelper();
- client = new AsyncHttpClient();
- variant = "price";
- sh.setVariant(variant);
- createViews();
- }
- private void createViews() {
- setUpSpinners();
- //set sales y axis label
- tvSalesYAaxis.setText("TOTAL PRICES");
- initializeSalesMPChart(sh.sales_values(), sh.hour_labels(), "hours");
- initializeProductPieChart(sh.products_values(), sh.product_labels());
- initializeCustomerPieChart(sh.customer_values(), sh.customer_labels());
- initializeStaffPieChart(sh.staff_values(), sh.staff_labels());
- //display totals
- displayTotalAmount();
- //check for connectivity
- ConnectivityManager cm =
- (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
- boolean isConnected = activeNetwork != null &&
- activeNetwork.isConnectedOrConnecting();
- if (isConnected) {
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
- + day_spinner.getSelectedItem();
- getDataFrom(date, "hours");
- } else {
- Crouton.makeText(Reports.this, "Check your network connection",
- Style.ALERT, com.duka.R.id.report_holder).show();
- }
- // initializeExpensesMPChart(sh.values(), sh.hour_labels());
- }
- private void initializeSalesMPChart(ArrayList<Entry> values, ArrayList<String> labels, String period) {
- Log.d("report_api_", "api_request displaying in chart");
- CustomMarkerView mv = new CustomMarkerView(this, getApplicationContext(),
- R.layout.custom_marker_view_layout, "sales", labels, period, variant);
- // set the marker to the chart
- salesLineChart.setMarkerView(mv);
- // mpChart.setOnChartGestureListener(this);
- // mpChart.setOnChartValueSelectedListener(this);
- // ArrayList<Entry> values = new ArrayList<>();
- //x,y
- /* values.add(new Entry(5, 10));
- values.add(new Entry(2, 4));
- values.add(new Entry(6, 10));
- values.add(new Entry(3, 1));
- values.add(new Entry(6, 10));
- values.add(new Entry(7, 13));
- values.add(new Entry(9, 7));*/
- LineDataSet report = new LineDataSet(values, "Records");
- /*report.setAxisDependency(YAxis.AxisDependency.LEFT);
- report.setColor(getResources().getColor(R.color.green_color));
- report.setCircleColor(Color.RED);
- report.setCircleColorHole(Color.RED);
- report.setCircleRadius(2f);
- report.setHighLightColor(Color.parseColor("#448AFF"));*/
- report.setColor(getResources().getColor(R.color.colorPrimary));
- // report.setColor(Color.parseColor("#758cbb"));
- // report.setColor(getResources().getColor(R.color.green_color));
- // report.setCircleColor(Color.BLACK);
- report.setCircleColor(Color.parseColor("#ffc755"));
- report.setLineWidth(3f);
- report.setCircleSize(3f);
- // report.setFillAlpha(10);
- report.setFillColor(Color.parseColor("#2d374c"));
- // report.setDrawCircles(true);
- // report.setValueTextSize(-5f);
- report.setValueTextSize(0f);
- ArrayList<ILineDataSet> dataSets = new ArrayList<>();
- dataSets.add(report);
- LineData data = new LineData(labels, dataSets);
- data.setValueFormatter(new CustomValueFormatter());
- XAxis xAxis = salesLineChart.getXAxis();
- xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
- xAxis.setTextSize(10f);
- xAxis.setDrawAxisLine(true);
- xAxis.setDrawGridLines(false);
- xAxis.setTextSize(9);
- // if (period.equals("hours")) {
- //
- // }
- // if (period.equals("days")) {
- // xAxis.setLabelsToSkip(1);
- // }
- // if (period.equals("months")) {
- //
- // }
- Legend l = salesLineChart.getLegend();
- l.setEnabled(false);
- //indicates if auto scaling on the y axis is enabled
- // salesLineChart.setAutoScaleMinMaxEnabled(true);
- salesLineChart.setDescription("");
- // if disabled, scaling can be done on x- and y-axis separately
- salesLineChart.setPinchZoom(true);
- salesLineChart.setDrawBorders(false);
- /*
- salesLineChart.setVisibleXRangeMinimum(4);*/
- salesLineChart.setBorderColor(getResources().getColor(R.color.grey_medium));
- salesLineChart.setScaleEnabled(true);
- salesLineChart.setTouchEnabled(true);
- salesLineChart.setDragEnabled(true);
- salesLineChart.setDoubleTapToZoomEnabled(false);
- salesLineChart.getAxisLeft().setEnabled(true);
- salesLineChart.getAxisLeft().setTextColor(getResources().getColor(R.color.grey_medium));
- salesLineChart.getAxisRight().setEnabled(false);
- salesLineChart.getXAxis().setEnabled(true);
- salesLineChart.getAxisLeft().setAxisLineColor(getResources().getColor(R.color.grey_medium));
- salesLineChart.getAxisLeft().setGridColor(getResources().getColor(R.color.grey_medium));
- salesLineChart.getXAxis().setAxisLineColor(getResources().getColor(R.color.grey_medium));
- salesLineChart.getXAxis().setGridColor(getResources().getColor(R.color.grey_medium));
- salesLineChart.getXAxis().setTextColor(getResources().getColor(R.color.grey_medium));
- salesLineChart.animateXY(2000, 2000);
- salesLineChart.setNoDataTextDescription("No data available");
- //salesLineChart.invalidate();
- salesLineChart.notifyDataSetChanged();
- salesLineChart.invalidate();
- salesLineChart.setData(data);
- Log.d("array_report", "done setting sales to graph");
- }
- private void initializeProductPieChart(ArrayList<Entry> p_entries, final ArrayList<String> product_names) {
- /* ArrayList<Entry> entries = new ArrayList<>();
- entries.add(new Entry(4f, 0));
- entries.add(new Entry(8f, 1));
- entries.add(new Entry(6f, 2));
- entries.add(new Entry(12f, 3));
- entries.add(new Entry(18f, 4));
- entries.add(new Entry(9f, 5));*/
- PieDataSet dataset = new PieDataSet(p_entries, "");
- /* ArrayList<String> labels = new ArrayList<String>();
- labels.add("January");
- labels.add("February");
- labels.add("March");
- labels.add("April");
- labels.add("May");
- labels.add("June");*/
- l = product_pieChart.getLegend();
- product_pieChart.getLegend().setWordWrapEnabled(true);
- l.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT);
- l.setXEntrySpace(15f);
- l.setYEntrySpace(0f);
- l.setYOffset(0f);
- Log.d("legend_", Arrays.toString(l.getColors()) + "/" + Arrays.toString(l.getLabels()));
- PieData data = new PieData(product_names, dataset);
- // add a lot of colors
- ArrayList<Integer> colors = new ArrayList<Integer>();
- for (int c : ColorTemplate.VORDIPLOM_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.PASTEL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.COLORFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.JOYFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.LIBERTY_COLORS)
- colors.add(c);
- colors.add(ColorTemplate.getHoloBlue());
- dataset.setColors(colors);
- // data.setValueTextSize(0);
- // dataset.setColors(getResources().getIntArray(R.array.androidcolors));
- dataset.setSliceSpace(0);
- data.setValueFormatter(new PercentagesValueFormatter());
- product_pieChart.setDragDecelerationFrictionCoef(0.95f);
- product_pieChart.setDescription("");
- product_pieChart.setUsePercentValues(true);
- product_pieChart.setData(data);
- product_pieChart.animateY(2000);
- product_pieChart.setDescriptionTextSize(0);
- product_pieChart.setDrawSliceText(false);
- product_pieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
- @Override
- public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
- Log.d("chart_data", e.getXIndex() + "/" + product_names.get(e.getXIndex()));
- // piechartCheck = piechartCheck + 1;
- // if (piechartCheck > 1) {
- tvProductsData.setVisibility(View.VISIBLE);
- if (variant.equals("price")) {
- tvProductsData.setText(product_names.get(e.getXIndex()));
- } else {
- tvProductsData.setText(product_names.get(e.getXIndex()));
- }
- // }
- }
- @Override
- public void onNothingSelected() {
- }
- });
- }
- private void initializeCustomerPieChart(ArrayList<Entry> c_entries, ArrayList<String> customer_names) {
- PieDataSet dataset = new PieDataSet(c_entries, "");
- /* ArrayList<String> labels = new ArrayList<String>();
- labels.add("January");
- labels.add("February");
- labels.add("March");
- labels.add("April");
- labels.add("May");
- labels.add("June");*/
- Legend l = customer_pieChart.getLegend();
- customer_pieChart.getLegend().setWordWrapEnabled(true);
- l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
- l.setXEntrySpace(7f);
- l.setYEntrySpace(0f);
- l.setYOffset(0f);
- PieData data = new PieData(customer_names, dataset);
- // add a lot of colors
- ArrayList<Integer> colors = new ArrayList<Integer>();
- for (int c : ColorTemplate.VORDIPLOM_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.PASTEL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.COLORFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.JOYFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.LIBERTY_COLORS)
- colors.add(c);
- colors.add(ColorTemplate.getHoloBlue());
- colors.add(ColorTemplate.getHoloBlue());
- data.setValueFormatter(new PercentagesValueFormatter());
- dataset.setColors(colors);
- // dataset.setColors(getResources().getIntArray(R.array.androidcolors));
- // dataset.setColors(ColorTemplate.COLORFUL_COLORS); //
- customer_pieChart.setDescription("");
- customer_pieChart.setDragDecelerationFrictionCoef(0.95f);
- customer_pieChart.setDescription("");
- customer_pieChart.setUsePercentValues(true);
- customer_pieChart.setData(data);
- customer_pieChart.setDescriptionTextSize(0);
- customer_pieChart.setDrawSliceText(false);
- customer_pieChart.animateY(2000);
- }
- private void initializeStaffPieChart(ArrayList<Entry> entries, ArrayList<String> staff_names) {
- PieDataSet dataset = new PieDataSet(entries, "");
- Legend l = staff_pieChart.getLegend();
- staff_pieChart.getLegend().setWordWrapEnabled(true);
- l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
- l.setXEntrySpace(7f);
- l.setYEntrySpace(0f);
- l.setYOffset(0f);
- PieData data = new PieData(staff_names, dataset);
- // add a lot of colors
- ArrayList<Integer> colors = new ArrayList<Integer>();
- for (int c : ColorTemplate.VORDIPLOM_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.PASTEL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.COLORFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.JOYFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.LIBERTY_COLORS)
- colors.add(c);
- colors.add(ColorTemplate.getHoloBlue());
- colors.add(ColorTemplate.getHoloBlue());
- data.setValueFormatter(new PercentagesValueFormatter());
- dataset.setColors(colors);
- // dataset.setColors(getResources().getIntArray(R.array.androidcolors));
- // dataset.setColors(ColorTemplate.COLORFUL_COLORS); //
- staff_pieChart.setDescription("");
- staff_pieChart.setDragDecelerationFrictionCoef(0.95f);
- staff_pieChart.setDescription("");
- staff_pieChart.setUsePercentValues(true);
- staff_pieChart.setData(data);
- staff_pieChart.setDescriptionTextSize(0);
- staff_pieChart.setDrawSliceText(false);
- staff_pieChart.animateY(2000);
- }
- private void setUpSpinners() {
- //for year spinner
- yearSpinner();
- //for month spinner
- monthSpinner();
- //for day spinner
- daySpinner(true);
- }
- public void setCustomLegend() {
- }
- private void yearSpinner() {
- List<String> year_spinner_array = new ArrayList<>();
- Calendar c3 = Calendar.getInstance();
- c3.add(Calendar.MONTH, -1);
- c3.add(Calendar.DAY_OF_MONTH, -1);
- SimpleDateFormat mFormat3 = new SimpleDateFormat("yyyy", Locale.US);
- int year = Integer.parseInt(mFormat3.format(c3.getTime()));
- year_spinner_array.add(0, String.valueOf(year - 4));
- year_spinner_array.add(0, String.valueOf(year - 3));
- year_spinner_array.add(0, String.valueOf(year - 2));
- year_spinner_array.add(0, String.valueOf(year - 1));
- year_spinner_array.add(0, String.valueOf(year));
- ArrayAdapter<String> spinnerArrayAdapter3 = new ArrayAdapter<String>(this,
- R.layout.period_spinner_item, year_spinner_array);
- //selected item will look like a spinner set from XML
- spinnerArrayAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- year_spinner.setAdapter(spinnerArrayAdapter3);
- year_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
- yearCheck = yearCheck + 1;
- if (yearCheck > 1) {
- // date = (String) adapterView.getItemAtPosition(i);
- if (isMonth && isYear) {
- if (isDay) {
- date = year_spinner.getSelectedItem() + "/"
- + month_spinner.getItemAtPosition(i) + "/"
- + day_spinner.getSelectedItem();
- getDataFrom(date, "months");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- } else {
- date = (String) adapterView.getItemAtPosition(i) + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem());
- getDataFrom(date, "months");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- }
- } else {
- date = (String) adapterView.getItemAtPosition(i);
- getDataFrom(date, "months");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- }
- }
- }
- @Override
- public void onNothingSelected(AdapterView<?> adapterView) {
- }
- });
- }
- private void monthSpinner() {
- /* List<String> month_spinner_array = new ArrayList<>();
- Calendar c2 = Calendar.getInstance();
- c2.add(Calendar.MONTH, -1);
- c2.add(Calendar.DAY_OF_MONTH, -1);
- SimpleDateFormat mFormat2 = new SimpleDateFormat("MM", Locale.US);
- while (c2.before(Calendar.getInstance())) {
- month_spinner_array.add(0, mFormat2.format(c2.getTime()));
- c2.add(Calendar.DAY_OF_MONTH, 1);
- }
- */
- Calendar c2 = Calendar.getInstance();
- c2.add(Calendar.MONTH, 0);
- c2.add(Calendar.DAY_OF_MONTH, 0);
- SimpleDateFormat mFormat2 = new SimpleDateFormat("MMMM", Locale.US);
- String month = mFormat2.format(c2.getTime());
- if (month.startsWith("0")) {
- final_month = mFormat2.format(c2.getTime()).replace("0", "");
- } else {
- final_month = mFormat2.format(c2.getTime());
- }
- month_spinner_array = getResources().getStringArray(R.array.month_name_arrays);
- ArrayAdapter<String> spinnerArrayAdapter2 = new ArrayAdapter<String>(this,
- R.layout.period_spinner_item, month_spinner_array);
- //selected item will look like a spinner set from XML
- spinnerArrayAdapter2.setDropDownViewResource(R.layout.period_spinner_dropdown_item);
- month_spinner.setAdapter(spinnerArrayAdapter2);
- month_spinner.setSelection(((ArrayAdapter) month_spinner.getAdapter()).getPosition(month));
- month_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
- monthCheck = monthCheck + 1;
- if (monthCheck > 1) {
- // date = (String) adapterView.getItemAtPosition(i);
- // daySpinner(false);
- if (isMonth && isYear) {
- if (isDay) {
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
- + day_spinner.getSelectedItem();
- getDataFrom(date, "days");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- } else {
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem());
- getDataFrom(date, "days");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- }
- }
- }
- }
- @Override
- public void onNothingSelected(AdapterView<?> adapterView) {
- }
- });
- }
- private void daySpinner(final boolean b) {
- Calendar c = Calendar.getInstance();
- c.add(Calendar.MONTH, -1);
- c.add(Calendar.DAY_OF_MONTH, 0);
- SimpleDateFormat mFormat = new SimpleDateFormat("dd", Locale.US);
- // while (c.before(Calendar.getInstance())) {
- //// day_spinner_array.add(0, mFormat.format(c.getTime()));
- // c.add(Calendar.DAY_OF_MONTH, 1);
- // }
- String today = mFormat.format(c.getTime());
- // if () {
- // day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- // }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("1")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("2")) {
- day_spinner_array = getResources().getStringArray(R.array.days_28_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("3")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("4")) {
- day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("5")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("6")) {
- day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("7")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("8")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("9")) {
- day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("10")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("11")) {
- day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("12")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- Log.d("month_position", monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()));
- // day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,
- R.layout.period_spinner_item, day_spinner_array);
- //
- // //selected item will look like a spinner set from XML
- spinnerArrayAdapter.setDropDownViewResource(R.layout.period_spinner_dropdown_item);
- day_spinner.setAdapter(spinnerArrayAdapter);
- day_spinner.setSelection(((ArrayAdapter) day_spinner.getAdapter()).getPosition(today));
- day_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
- if (b) {
- dayCheck = dayCheck + 1;
- if (dayCheck > 1) {
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
- + (String) adapterView.getItemAtPosition(i);
- getDataFrom(date, "hours");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- }
- }
- }
- @Override
- public void onNothingSelected(AdapterView<?> adapterView) {
- }
- });
- }
- private void displayTotalAmount() {
- DecimalFormat priceFormat = new DecimalFormat("###,###,###.00");
- DecimalFormat quantityFormat = new DecimalFormat("###,###,###");
- String total = "";
- if (variant.equals("price")) {
- total = String.valueOf(priceFormat.format(sh.getTotalSales()));
- if (total.equals(".00")) {
- tvSalesTotals.setText(asp.getCurrency() + " " + "0.00");
- tvProductsTotals.setText(asp.getCurrency() + " " + "0.00");
- tvCustomerTotals.setText(asp.getCurrency() + " " + "0.00");
- tvStaffTotals.setText(asp.getCurrency() + " " + "0.00");
- } else {
- tvSalesTotals.setText(asp.getCurrency() + " " + total);
- tvProductsTotals.setText(asp.getCurrency() + " " + total);
- tvCustomerTotals.setText(asp.getCurrency() + " " + total);
- tvStaffTotals.setText(asp.getCurrency() + " " + total);
- }
- } else {
- total = String.valueOf(quantityFormat.format(Double.valueOf(sh.getTotalQuantityOfProducts())));
- tvSalesTotals.setText(total + " Products");
- tvProductsTotals.setText(total + " Products");
- tvCustomerTotals.setText(total + " Products");
- tvStaffTotals.setText(total + " Products");
- }
- }
- private void getDataFrom(String period, final String label) {
- Log.d("report_api_", "api_request made");
- client.cancelAllRequests(true);
- client.cancelRequests(getApplicationContext(), true);
- ConnectivityManager cm =
- (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
- boolean isConnected = activeNetwork != null &&
- activeNetwork.isConnectedOrConnecting();
- if (isConnected) {
- String url = getResources().getString(R.string.url) + "sales/" + period
- + "/api";
- RequestParams params = new RequestParams();
- client.addHeader("class", "Business");
- client.addHeader("attendant_name", asp.getAttendantName());
- client.addHeader("attendant_id", asp.getAttendantId());
- client.addHeader(getResources().getString(R.string.api_token), asp.getApiKey());
- client.get(url,
- params, new AsyncHttpResponseHandler() {
- @Override
- public void onStart() {
- Log.d("report_api_", "api_request started");
- progressBar.setVisibility(View.VISIBLE);
- }
- @Override
- public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
- String s = new String(responseBody);
- progressBar.setVisibility(View.INVISIBLE);
- Log.d("sale_reports_", s);
- try {
- Log.d("report_api_", "api_request successful");
- JSONObject objs = new JSONObject(s);
- HashMap<String, String> map = new HashMap<String, String>();
- Boolean success = objs.getBoolean("success");
- if (success) {
- period_label = label;
- salesArray = objs.getJSONArray("data");
- sh.setLabelType(label);
- new AsyncUpdateSalesToDisplayGraph(salesArray, label).execute();
- } else {
- String failure = objs.getString("message");
- Crouton.makeText(
- Reports.this,
- failure,
- Style.ALERT, com.duka.R.id.report_holder).show();
- }
- } catch (JSONException e) {
- }
- }
- @Override
- public void onFailure(int statusCode, Header[] headers,
- byte[] responseBody, Throwable error) {
- progressBar.setVisibility(View.INVISIBLE);
- Log.d("something_went_wrong", String.valueOf(error));
- //errorDialog();
- Crouton.makeText(Reports.this, "Check your network connection",
- Style.ALERT, com.duka.R.id.report_holder).show();
- }
- }
- );
- } else {
- Crouton.makeText(Reports.this, "Check your network connection",
- Style.ALERT, com.duka.R.id.report_holder).show();
- }
- }
- public void onRadioButtonClicked(View view) {
- // Is the button now checked?
- boolean checked = ((RadioButton) view).isChecked();
- // Check which radio button was clicked
- switch (view.getId()) {
- case R.id.hour_radioBtn:
- if (checked) {
- dayButton.setChecked(false);
- monthButton.setChecked(false);
- layout1.setVisibility(View.VISIBLE);
- layout2.setVisibility(View.VISIBLE);
- layout3.setVisibility(View.VISIBLE);
- isDay = true;
- isMonth = true;
- isYear = true;
- setUpRequestForPeriod("hour");
- }
- break;
- case R.id.day_radioBtn:
- if (checked) {
- hourButton.setChecked(false);
- monthButton.setChecked(false);
- layout3.setVisibility(View.VISIBLE);
- layout1.setVisibility(View.VISIBLE);
- layout2.setVisibility(View.GONE);
- isDay = false;
- isMonth = true;
- isYear = true;
- setUpRequestForPeriod("days");
- }
- break;
- case R.id.month_radioBtn:
- if (checked) {
- dayButton.setChecked(false);
- hourButton.setChecked(false);
- layout1.setVisibility(View.VISIBLE);
- layout2.setVisibility(View.GONE);
- layout3.setVisibility(View.GONE);
- isDay = false;
- isMonth = false;
- isYear = true;
- setUpRequestForPeriod("months");
- }
- break;
- case R.id.price_radioBtn:
- if (checked) {
- quantitiesButton.setChecked(false);
- variant = "price";
- sh.setVariant(variant);
- getChartDataDependingOnVariant();
- }
- break;
- case R.id.quantities_radioBtn:
- if (checked) {
- priceButton.setChecked(false);
- variant = "quantity";
- sh.setVariant(variant);
- getChartDataDependingOnVariant();
- }
- break;
- }
- }
- private void getChartDataDependingOnVariant() {
- //if array is null, let's get data for today
- try {
- if (salesArray != null) {
- new AsyncUpdateSalesToDisplayGraph(salesArray, period_label).execute();
- } else {
- //display totals
- displayTotalAmount();
- //start local charts
- initializeSalesMPChart(sh.sales_values(), sh.hour_labels(), "hours");
- initializeProductPieChart(sh.products_values(), sh.product_labels());
- initializeCustomerPieChart(sh.customer_values(), sh.customer_labels());
- initializeStaffPieChart(sh.staff_values(), sh.staff_labels());
- //set sales y axis label
- if (variant.equals("price")) {
- tvSalesYAaxis.setText("TOTAL PRICES");
- } else {
- tvSalesYAaxis.setText("SALES");
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- private void setUpRequestForPeriod(String period) {
- if (period.equals("hours")) {
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
- + day_spinner.getSelectedItem();
- } else if (period.equals("days")) {
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem());
- } else {
- date = year_spinner.getSelectedItem() + "";
- }
- getDataFrom(date, period);
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- //noinspection SimplifiableIfStatement
- if (id == android.R.id.home) {
- finish();
- // MainActivity ma = new MainActivity();
- // ma.openResideMenu();
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
- private String getDayFormatted(String dateStr) {
- DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- DateFormat writeFormat = new SimpleDateFormat("dd");
- Date date = null;
- try {
- date = readFormat.parse(dateStr);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- String formattedDate = writeFormat.format(date);
- return formattedDate;
- }
- private String getTimeFormattedInAMPM(String dateStr) {
- DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- DateFormat writeFormat = new SimpleDateFormat("ha");
- Date date = null;
- try {
- date = readFormat.parse(dateStr);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- String formattedDate = writeFormat.format(date);
- return formattedDate;
- }
- private String getMonthFormatted(String dateStr) {
- DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- DateFormat writeFormat = new SimpleDateFormat("MMM ");
- Date date = null;
- try {
- date = readFormat.parse(dateStr);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- String formattedDate = writeFormat.format(date);
- return formattedDate;
- }
- String getCurrentDate() {
- Date now = new Date();
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
- return sdf.format(now);
- }
- private void showTotalsOnGraphs(ArrayList<String> sales_totals, ArrayList<String> product_totals, ArrayList<String> customer_totals, ArrayList<String> staff_totals) {
- double sum = 0;
- String unformatted_number = "";
- DecimalFormat priceFormat = new DecimalFormat("###,###,###.00");
- DecimalFormat quantityFormat = new DecimalFormat("###,###,###");
- String total = "";
- //sales totals
- for (int i = 0; i < sales_totals.size(); i++) {
- sum += Double.valueOf(sales_totals.get(i));
- }
- if (variant.equals("price")) {
- total = String.valueOf(priceFormat.format(sum));
- if (total.equals(".00")) {
- tvSalesTotals.setText(asp.getCurrency() + " " + "0.00");
- } else {
- tvSalesTotals.setText(asp.getCurrency() + " " + total);
- }
- } else {
- total = String.valueOf(quantityFormat.format(sum));
- tvSalesTotals.setText(total + " Products");
- }
- //products
- for (int i = 0; i < product_totals.size(); i++) {
- sum += Double.valueOf(product_totals.get(i));
- }
- if (variant.equals("price")) {
- total = String.valueOf(priceFormat.format(sum));
- if (total.equals(".00")) {
- tvProductsTotals.setText(asp.getCurrency() + " " + "0.00");
- } else {
- tvProductsTotals.setText(asp.getCurrency() + " " + total);
- }
- } else {
- total = String.valueOf(quantityFormat.format(sum));
- tvProductsTotals.setText(total + " Products");
- }
- //customers
- for (int i = 0; i < customer_totals.size(); i++) {
- sum += Double.valueOf(customer_totals.get(i));
- }
- if (variant.equals("price")) {
- total = String.valueOf(priceFormat.format(sum));
- if (total.equals(".00")) {
- tvCustomerTotals.setText(asp.getCurrency() + " " + "0.00");
- } else {
- tvCustomerTotals.setText(asp.getCurrency() + " " + total);
- }
- } else {
- total = String.valueOf(quantityFormat.format(sum));
- tvCustomerTotals.setText(total + " Products");
- }
- //staff
- for (int i = 0; i < staff_totals.size(); i++) {
- sum += Double.valueOf(staff_totals.get(i));
- }
- if (variant.equals("price")) {
- total = String.valueOf(priceFormat.format(sum));
- if (total.equals(".00")) {
- tvStaffTotals.setText(asp.getCurrency() + " " + "0.00");
- } else {
- tvStaffTotals.setText(asp.getCurrency() + " " + total);
- }
- } else {
- total = String.valueOf(quantityFormat.format(sum));
- tvStaffTotals.setText(total + " Products");
- }
- }
- public static class SortBasedOnCreatedAt implements Comparator<JSONObject> {
- String CompareString1 = "", CompareString2 = "";
- /*
- * (non-Javadoc)
- *
- * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
- * lhs- 1st message in the form of json object. rhs- 2nd message in the form
- * of json object.
- */
- @Override
- public int compare(JSONObject lhs, JSONObject rhs) {
- try {
- // return Integer.valueOf(lhs.getString("created_at")) > Integer.valueOf(rhs.getString("created_at"))
- // ? 1 : (Integer.valueOf(lhs.getString("created_at")) < Integer.valueOf(rhs.getString("created_at")) ? -1 : 0);
- CompareString1 = lhs.getString("created_at"); //Key must be present in JSON
- CompareString2 = rhs.getString("created_at"); //Key must be present in JSON
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return CompareString1.compareTo(CompareString2);
- }
- }
- class AsyncUpdateSalesToDisplayGraph extends AsyncTask<Void, String, Void> {
- Activity activity;
- JSONArray sales;
- JSONObject sale_obj;
- ArrayList<String> sales_labels = new ArrayList<>();
- ArrayList<String> sales_totals = new ArrayList<>();
- ArrayList<Entry> sales_values = new ArrayList<>();
- ArrayList<String> product_names = new ArrayList<>();
- ArrayList<String> product_labelz = new ArrayList<>();
- ArrayList<String> product_totals = new ArrayList<>();
- ArrayList<Entry> product_values = new ArrayList<>();
- ArrayList<String> customer_names = new ArrayList<>();
- ArrayList<String> customer_labelz = new ArrayList<>();
- ArrayList<String> customer_totals = new ArrayList<>();
- ArrayList<Entry> customer_values = new ArrayList<>();
- ArrayList<String> staff_names = new ArrayList<>();
- ArrayList<String> staff_labelz = new ArrayList<>();
- ArrayList<String> staff_totals = new ArrayList<>();
- ArrayList<Entry> staff_values = new ArrayList<>();
- int maxLength;
- String label, product_label_to_truncate, customer_label_to_truncate, staff_label_to_truncate;
- public AsyncUpdateSalesToDisplayGraph(JSONArray sale, String label) throws JSONException {
- this.sales = getSortedListByDate(sale);
- this.label = label;
- }
- @Override
- protected void onPreExecute() {
- Crouton.makeText(
- Reports.this,
- "Processing the data...",
- Style.INFO, com.duka.R.id.report_holder).show();
- }
- @Override
- protected Void doInBackground(Void... params) {
- Log.d("array_report_track", "adding sales in background");
- Log.d("array_report_track", "adding sales in background");
- JSONObject groupedSales = new JSONObject();
- JSONObject groupedProducts = new JSONObject();
- JSONObject groupedCustomers = new JSONObject();
- JSONObject groupedStaff = new JSONObject();
- JSONArray groupedSalesArray = new JSONArray();
- DecimalFormat priceFormat = new DecimalFormat("###,###,###");
- DecimalFormat quantityFormat = new DecimalFormat("###,###,###");
- for (int i = 0; i < sales.length(); i++) {
- try {
- sale_obj = (JSONObject) sales.get(i);
- int id = sale_obj.getInt("id");
- //update local db for today only
- if (date.equals(getCurrentDate())) {
- String attendant_id = sale_obj.getString("attendant_id");
- String attendant_name = sale_obj.getString("attendant_name");
- String business_id = sale_obj.getString("business_id");
- String created_at = sale_obj.getString("created_at");
- String customer_first_name = sale_obj.getString("customer_first_name");
- String customer_id = sale_obj.getString("customer_id");
- String customer_image = sale_obj.getString("customer_image");
- String customer_last_name = sale_obj.getString("customer_last_name");
- String image = sale_obj.getString("image");
- String name = sale_obj.getString("name");
- String price = sale_obj.getString("price");
- String product_id = sale_obj.getString("product_id");
- String quantity = sale_obj.getString("quantity");
- String reader_id = sale_obj.getString("reader_id");
- String svg = sale_obj.getString("svg");
- String synced_at = sale_obj.getString("synced_at");
- String time_code = sale_obj.getString("time_code");
- String uid = sale_obj.getString("uid");
- String updated_at = sale_obj.getString("updated_at");
- String deleted_at = sale_obj.getString("deleted_at");
- sh.updateSingleSale(String.valueOf(id), attendant_id, attendant_name,
- product_id, price, customer_id, customer_first_name,
- customer_last_name, customer_image, uid, quantity,
- name, image, created_at, deleted_at, svg, "false", time_code);
- }
- double total = sale_obj.getDouble(variant); // variant is price or quantity
- // sales line graph
- String period = ""; // hour|date|month e.g. 9AM|31|October
- if (label.equals("hours")) {
- period = getTimeFormattedInAMPM(sale_obj.getString("created_at")); // hour
- }
- if (label.equals("days")) {
- period = getDayFormatted(sale_obj.getString("created_at")); // date
- }
- if (label.equals("months")) {
- period = getMonthFormatted(sale_obj.getString("created_at")); // month
- }
- int index = sales_labels.indexOf(period);
- if (index < 0) { // doesnt exist in sales_label_1
- sales_labels.add(period);
- sales_values.add(new Entry((float) total, sales_labels.size() - 1));
- } else {
- // read the current total
- double current_total = groupedSales.getDouble(period);
- // increment by the sale_obj total
- total = current_total + total;
- sales_values.set(index, new Entry((float) total, index));
- }
- sales_totals.add(sale_obj.getString(variant));
- groupedSales.put(period, total);
- Log.d("array_report_sales", groupedSales.toString());
- // products pie chart
- String productName = sale_obj.getString("name");
- index = product_names.indexOf(productName);
- product_label_to_truncate = String.valueOf(priceFormat.format(total)) + " " + productName;
- if (index < 0) {
- // product doesnt exist in product_labelz
- product_names.add(productName);
- product_labelz.add(product_label_to_truncate);
- product_values.add(new Entry((float) total, product_labelz.size() - 1));
- } else {
- // read the current total
- double current_total = groupedProducts.getDouble(productName);
- // increment by the total
- total = current_total + total;
- product_values.set(index, new Entry((float) total, index));
- }
- product_totals.add(sale_obj.getString(variant));
- groupedProducts.put(productName, total);
- Log.d("array_report_products", groupedProducts.toString());
- // customers pie chart
- String customerName = sale_obj.getString("customer_first_name") + " "
- + sale_obj.getString("customer_last_name");
- index = customer_names.indexOf(customerName);
- customer_label_to_truncate = String.valueOf(quantityFormat.format(total)) + " " + customerName;
- if (index < 0) {
- // customer doesnt exist in customer_labelz
- customer_names.add(customerName);
- customer_labelz.add(customer_label_to_truncate);
- customer_values.add(new Entry((float) total, customer_labelz.size() - 1));
- } else {
- // read the current total
- double current_total = groupedCustomers.getDouble(customerName);
- // increment by the total
- total = current_total + total;
- customer_values.set(index, new Entry((float) total, index));
- }
- customer_totals.add(sale_obj.getString(variant));
- groupedCustomers.put(customerName, total);
- Log.d("array_report_customer", groupedCustomers.toString());
- // staff pie chart
- String staffName = sale_obj.getString("attendant_name");
- index = staff_names.indexOf(staffName);
- staff_label_to_truncate = String.valueOf(priceFormat.format(total)) + " " + staffName;
- if (index < 0) {
- // staff doesnt exist in staff_labelz
- staff_names.add(staffName);
- staff_labelz.add(staff_label_to_truncate);
- staff_values.add(new Entry((float) total, staff_labelz.size() - 1));
- } else {
- // read the current total
- double current_total = groupedStaff.getDouble(staffName);
- // increment by the total
- total = current_total + total;
- staff_values.set(index, new Entry((float) total, index));
- }
- staff_totals.add(sale_obj.getString(variant));
- groupedStaff.put(staffName, total);
- Log.d("array_report_staff", groupedStaff.toString());
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- Log.d("array_report_track", "done adding sales in background" + groupedSalesArray.toString());
- Log.d("array_report_sales", sales_labels.toString() + "///" + sales_values.toString());
- return null;
- }
- @Override
- protected void onPostExecute(Void unused) {
- //totals
- showTotalsOnGraphs(sales_totals, product_totals, customer_totals, staff_totals);
- Log.d("sum_sales_values", sales_values.toString() + "/" + sales_labels.toString());
- if (label.equals("hours")) {
- salesXTitle.setText("TIME");
- }
- if (label.equals("days")) {
- salesXTitle.setText("DATES");
- }
- if (label.equals("months")) {
- salesXTitle.setText("MONTHS");
- }
- //set sales y axis label
- if (variant.equals("price")) {
- tvSalesYAaxis.setText("TOTAL PRICES");
- } else {
- tvSalesYAaxis.setText("SALES");
- }
- initializeSalesMPChart(sales_values, sales_labels, label);
- initializeProductPieChart(product_values, product_labelz);
- initializeCustomerPieChart(customer_values, customer_labelz);
- initializeStaffPieChart(staff_values, staff_labelz);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement