Advertisement
stevekamau

Untitled

Jan 8th, 2017
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 62.09 KB | None | 0 0
  1. package dataBaseHandlers;
  2.  
  3. import android.content.ContentValues;
  4. import android.content.Context;
  5. import android.content.SharedPreferences;
  6. import android.database.Cursor;
  7. import android.database.sqlite.SQLiteDatabase;
  8. import android.database.sqlite.SQLiteOpenHelper;
  9. import android.util.Log;
  10.  
  11. import com.github.mikephil.charting.data.Entry;
  12. import com.google.gson.Gson;
  13. import com.google.gson.GsonBuilder;
  14.  
  15. import java.text.DateFormat;
  16. import java.text.DecimalFormat;
  17. import java.text.ParseException;
  18. import java.text.SimpleDateFormat;
  19. import java.util.ArrayList;
  20. import java.util.Date;
  21. import java.util.HashMap;
  22. import java.util.LinkedHashSet;
  23. import java.util.Set;
  24. import java.util.concurrent.locks.ReadWriteLock;
  25. import java.util.concurrent.locks.ReentrantReadWriteLock;
  26.  
  27. import model.SaleModel;
  28.  
  29. /**
  30.  * Created by steve on 7/3/16.
  31.  */
  32. public class SalesHandler extends SQLiteOpenHelper {
  33.     private static final String TAG = SalesHandler.class.getSimpleName();
  34.  
  35.     // Database Version
  36.     private static final int DATABASE_VERSION = 31;
  37.     // Database Name
  38.     private static final String DATABASE_NAME = "Sales";
  39.     // Table names
  40.     private static final String TABLE_SALES = "loadSales";
  41.     private static final String TABLE_MANY_SALES = "manySales";
  42.     private static final String TABLE_TOTAL_SALES = "total_sales";
  43.     private static final String TABLE_DELETE_SALES = "delete_sales";
  44.     private static final String TABLE_SALES_KEYS = "sales_keys";
  45.     private static final String TABLE_SALES_NOTIFICATIONS = "sales_notifications";
  46.  
  47.     // cCheckouts Table Columns names
  48.     private static final String KEY_ID = "id";
  49.     private static final String KEY_SID = "s_id";
  50.     private static final String KEY_TIME_CODE = "time_code";
  51.     private static final String KEY_ATTENDANT_ID = "attendant_id";
  52.     private static final String KEY_ATTENDANT_NAME = "attendant_name";
  53.     private static final String KEY_PRODUCT_ID = "product_id";
  54.     private static final String KEY_CUSTOMER_ID = "customer_id";
  55.     private static final String KEY_CUSTOMER_FIRST_NAME = "customer_first_name";
  56.     private static final String KEY_CUSTOMER_LAST_NAME = "customer_last_name";
  57.     private static final String KEY_CUSTOMER_IMAGE = "customer_image";
  58.     private static final String KEY_UID = "uid";
  59.     private static final String KEY_STATUS = "status";
  60.     private static final String KEY_PRICE = "price";
  61.     private static final String KEY_QUANTITY = "quantity";
  62.     private static final String KEY_PRODUCT_NAME = "p_name";
  63.     private static final String KEY_PRODUCT_IMAGE = "p_image";
  64.     private static final String KEY_CREATED_AT = "created_at";
  65.     private static final String KEY_CREATED_AT_AM_PM = "created_at_am_pm";
  66.     private static final String KEY_CREATED_AT_DAY = "created_at_day";
  67.     private static final String KEY_CREATED_AT_MONTH = "created_at_month";
  68.     private static final String KEY_CREATED_AT_YEAR = "created_at_year";
  69.     private static final String KEY_COUNT = "count";
  70.     private static final String KEY_DELETED_AT = "deleted_at";
  71.     private static final String KEY_OFFLINETAG = "offline_tag";
  72.     private static final String KEY_PRODUCT_JSON = "jsonProducts";
  73.     private static final String KEY_SVG = "svg";
  74.     private static final String KEY_CREATED_AT_DATE = "created_at_date";
  75.     private static final String KEY_UNIQUE = "unique_key";
  76.     private static final String KEY_POSITION = "position";
  77.     private static final String KEY_MESSAGE = "message";
  78.     private static final ReadWriteLock rwLock = new ReentrantReadWriteLock(true);
  79.     private static SalesHandler sInstance;
  80.     int pos = 0;
  81.     HashMap<String, String> map = new HashMap<String, String>();
  82.     ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
  83.     Context context;
  84.     double sum = 0;
  85.     int count = 0;
  86.     String set_variant;
  87.     HashMap<String, String> amountMap = new HashMap<String, String>();
  88.     ArrayList<String> amountArraylist = new ArrayList<String>();
  89.     ArrayList<String> hour_labels = new ArrayList<>();
  90.     ArrayList<String> product_labels = new ArrayList<>();
  91.     ArrayList<String> customer_labels = new ArrayList<>();
  92.     ArrayList<String> staff_labels = new ArrayList<>();
  93.     ArrayList<String> notificationsList = new ArrayList<String>();
  94.     ArrayList<String> sumQuantityList = new ArrayList<>();
  95.  
  96.     ArrayList<SaleModel> sales = new ArrayList<>();
  97.     String period_label;
  98.     DecimalFormat mFormat = new DecimalFormat("###,###,###");
  99.     private HashMap hp;
  100.  
  101.     public SalesHandler(Context context) {
  102.         super(context, DATABASE_NAME, null, DATABASE_VERSION);
  103.         this.context = context;
  104.     }
  105.  
  106.     public static synchronized SalesHandler getInstance(Context context) {
  107.  
  108.         // Use the application context, which will ensure that you
  109.         // don't accidentally leak an Activity's context.
  110.         // See this article for more information: http://bit.ly/6LRzfx
  111.         if (sInstance == null) {
  112.             sInstance = new SalesHandler(context.getApplicationContext());
  113.         }
  114.         return sInstance;
  115.     }
  116.  
  117.     private static void beginReadLock() {
  118.         rwLock.readLock().lock();
  119.     }
  120.  
  121.     private static void endReadLock() {
  122.         rwLock.readLock().unlock();
  123.     }
  124.  
  125.     private static void beginWriteLock() {
  126.         rwLock.writeLock().lock();
  127.     }
  128.  
  129.     private static void endWriteLock() {
  130.         rwLock.writeLock().unlock();
  131.     }
  132.  
  133.     @Override
  134.     public void onCreate(SQLiteDatabase db) {
  135.         String CREATE_SALES_TABLE = "CREATE TABLE " + TABLE_SALES + "("
  136.                 + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TIME_CODE + " TEXT," + KEY_ATTENDANT_ID + " TEXT," + KEY_SID + " TEXT," + KEY_ATTENDANT_NAME + " TEXT,"
  137.                 + KEY_PRODUCT_ID + " TEXT," + KEY_CUSTOMER_ID + " TEXT," + KEY_QUANTITY + " TEXT," + KEY_PRODUCT_NAME + " TEXT,"
  138.                 + KEY_PRODUCT_IMAGE + " TEXT," + KEY_CREATED_AT + " TEXT," + KEY_DELETED_AT + " TEXT," + KEY_PRICE + " TEXT," + KEY_UNIQUE + " TEXT unique,"
  139.                 + KEY_CUSTOMER_FIRST_NAME + " TEXT," + KEY_CUSTOMER_LAST_NAME + " TEXT," + KEY_CUSTOMER_IMAGE + " TEXT," + KEY_UID + " TEXT," + KEY_CREATED_AT_AM_PM + " TEXT,"
  140.                 + KEY_SVG + " TEXT," + KEY_CREATED_AT_DATE + " TEXT," + KEY_COUNT + " TEXT,"
  141.                 + KEY_OFFLINETAG + " TEXT" + ")";
  142.  
  143.         String CREATE_MANY_SALES_TABLE = "CREATE TABLE " + TABLE_MANY_SALES + "("
  144.                 + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ATTENDANT_ID + " TEXT," + KEY_ATTENDANT_NAME + " TEXT,"
  145.                 + KEY_CUSTOMER_ID + " TEXT," + KEY_PRODUCT_JSON + " TEXT," + KEY_CREATED_AT + " TEXT,"
  146.                 + KEY_PRICE + " TEXT," + KEY_OFFLINETAG + " TEXT," + KEY_STATUS + " TEXT," + KEY_TIME_CODE + " TEXT" + ")";
  147.  
  148.         String CREATE_TOTAL_SALES_AMOUNT = "CREATE TABLE " + TABLE_TOTAL_SALES + "("
  149.                 + KEY_ID + " INTEGER PRIMARY KEY," + KEY_QUANTITY + " TEXT," + KEY_CREATED_AT + " TEXT,"
  150.                 + KEY_CREATED_AT_DAY + " TEXT," + KEY_CREATED_AT_MONTH + " TEXT,"
  151.                 + KEY_CREATED_AT_YEAR + " TEXT," + KEY_COUNT + " TEXT," + KEY_ATTENDANT_ID + " TEXT,"
  152.                 + KEY_ATTENDANT_NAME + " TEXT," + KEY_PRICE + " TEXT,"
  153.                 + KEY_PRODUCT_ID + " TEXT," + KEY_PRODUCT_NAME + " TEXT," + KEY_CUSTOMER_ID + " TEXT,"
  154.                 + KEY_CUSTOMER_FIRST_NAME + " TEXT," + KEY_CUSTOMER_LAST_NAME + " TEXT,"
  155.                 + KEY_CREATED_AT_AM_PM + " TEXT" + ")";
  156.  
  157.         String CREATE_DELETED_SALES = "CREATE TABLE " + TABLE_DELETE_SALES + "("
  158.                 + KEY_ID + " INTEGER PRIMARY KEY," + KEY_POSITION + " INTEGER,"
  159.                 + KEY_SID + " TEXT" + ")";
  160.  
  161.         String CREATE_SALES_KEYS = "CREATE TABLE " + TABLE_SALES_KEYS + "("
  162.                 + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TIME_CODE + " TEXT" + ")";
  163.  
  164.         String CREATE_SALES_NOTIFICATIONS = "CREATE TABLE " + TABLE_SALES_NOTIFICATIONS + "("
  165.                 + KEY_ID + " INTEGER PRIMARY KEY," + KEY_QUANTITY + " TEXT," + KEY_MESSAGE + " TEXT" + ")";
  166.  
  167.         db.execSQL(CREATE_SALES_TABLE);
  168.         db.execSQL(CREATE_MANY_SALES_TABLE);
  169.         db.execSQL(CREATE_TOTAL_SALES_AMOUNT);
  170.         db.execSQL(CREATE_DELETED_SALES);
  171.         db.execSQL(CREATE_SALES_KEYS);
  172.         db.execSQL(CREATE_SALES_NOTIFICATIONS);
  173.  
  174.     }
  175.  
  176.     @Override
  177.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  178.         db.execSQL("DROP TABLE IF EXISTS " + TABLE_SALES);
  179.         db.execSQL("DROP TABLE IF EXISTS " + TABLE_MANY_SALES);
  180.         db.execSQL("DROP TABLE IF EXISTS " + TABLE_TOTAL_SALES);
  181.         db.execSQL("DROP TABLE IF EXISTS " + TABLE_DELETE_SALES);
  182.         db.execSQL("DROP TABLE IF EXISTS " + TABLE_SALES_KEYS);
  183.         db.execSQL("DROP TABLE IF EXISTS " + TABLE_SALES_NOTIFICATIONS);
  184.         // Create tables again
  185.         onCreate(db);
  186.     }
  187.  
  188.     /**
  189.      * Storing user details in database
  190.      */
  191.     public void addToDisplaySalesTable(SaleModel sale) {
  192.  
  193.         {
  194.             SQLiteDatabase db = null;
  195.  
  196.             try {
  197.                 beginWriteLock();
  198.                 db = this.getWritableDatabase();
  199.  
  200.                 /*this.getWritableDatabase();*/
  201.                 ContentValues values = new ContentValues();
  202.  
  203.                 values.put(KEY_SID, sale.getId());
  204.                 values.put(KEY_TIME_CODE, sale.getTime_code());
  205.                 values.put(KEY_ATTENDANT_ID, sale.getAttendant_id());
  206.                 values.put(KEY_ATTENDANT_NAME, sale.getAttendant_name());
  207.                 values.put(KEY_PRODUCT_ID, sale.getProduct_id());
  208.                 values.put(KEY_PRICE, sale.getPrice());  //price
  209.                 values.put(KEY_CUSTOMER_ID, sale.getCustomer_id());
  210.                 values.put(KEY_CUSTOMER_FIRST_NAME, sale.getCustomer_first_name());
  211.                 values.put(KEY_CUSTOMER_LAST_NAME, sale.getCustomer_last_name());
  212.                 values.put(KEY_CUSTOMER_IMAGE, sale.getCustomer_image());
  213.                 values.put(KEY_UID, sale.getUid());
  214.                 values.put(KEY_QUANTITY, sale.getQuantity());
  215.                 values.put(KEY_PRODUCT_NAME, sale.getName());
  216.                 values.put(KEY_PRODUCT_IMAGE, sale.getImage());
  217.                 values.put(KEY_CREATED_AT, sale.getCreated_at());
  218.                 values.put(KEY_DELETED_AT, sale.getDeleted_at());
  219.                 values.put(KEY_CREATED_AT_DATE, createdAtDate(sale.getCreated_at()));
  220.                 values.put(KEY_SVG, sale.getSvg());
  221.                 values.put(KEY_COUNT, "1");
  222.                 values.put(KEY_OFFLINETAG, sale.getOfflineTag());
  223.                 values.put(KEY_UNIQUE, sale.getUnique_key());
  224.  
  225.                 values.put(KEY_CREATED_AT_AM_PM, getTimeFormattedInAMPM(sale.getCreated_at()).replace("0", ""));
  226.  
  227. //        db.insertWithOnConflict(tableName, BaseColumns._ID, v, SQLiteDatabase.CONFLICT_REPLACE);
  228.                 long id = db.insertWithOnConflict(TABLE_SALES, KEY_UNIQUE, values, SQLiteDatabase.CONFLICT_REPLACE);
  229.  
  230.                 Log.d("addsale_ ", "addToDisplaySalesTable code" + sale.getTime_code());
  231.  
  232.                 Log.d(TAG, "New sale inserted into sqlite: " + id);
  233.  
  234.                 // clear Synced Sales of a previous date
  235.                 deletePreviousDaySales();
  236.  
  237.                 // Closing database connection
  238.                 // db.close();
  239.  
  240.             } catch (Exception e) {
  241.                 Log.d("addsale_exceptions1 ", e.toString());
  242.             } finally {
  243.                 if (db != null) {
  244.                     try {
  245.                         // db.close();
  246.                     } catch (Exception e) {
  247.                         Log.d("addsale_exceptions2", e.toString());
  248.                     }
  249.                 }
  250.                 endWriteLock();
  251.             }
  252.  
  253.         }
  254.     }
  255.  
  256.     public void deletePreviousDaySales() {
  257.         SQLiteDatabase db = this.getWritableDatabase();
  258.         db.execSQL("DELETE FROM " + TABLE_SALES + " WHERE `" + KEY_OFFLINETAG + "` = 'false' AND `"
  259.                 + KEY_CREATED_AT_DATE + "` != '" + getCurrentDate() + "'");
  260.     }
  261.  
  262.     String getCurrentDate() {
  263.         Date now = new Date();
  264.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  265.         return sdf.format(now);
  266.     }
  267.  
  268.     String createdAtDate(String created_at) {
  269.         Date createdAtDate = new Date();
  270.         try {
  271.             createdAtDate = new SimpleDateFormat("yyyy-MM-dd").parse(created_at);
  272.  
  273.         } catch (ParseException e) {
  274.             e.printStackTrace();
  275.         }
  276.         return new SimpleDateFormat("yyyy-MM-dd").format(createdAtDate);
  277.     }
  278.  
  279.     public ArrayList<SaleModel> displaySales() {
  280.         sales.clear();
  281.         hp = new HashMap();
  282.         ArrayList<SaleModel> sales = new ArrayList<>();
  283.         {
  284.             SQLiteDatabase db = null;
  285.  
  286.             try {
  287.                 beginReadLock();
  288.                 db = this.getWritableDatabase();
  289.                 Cursor res = db.rawQuery("SELECT  * FROM " + TABLE_SALES + " ORDER BY datetime(created_at) DESC", null);
  290.                 //Cursor res = db.rawQuery("SELECT  * FROM " + TABLE_SALES + " ORDER BY id ASC", null);
  291.                 //Cursor res = db.rawQuery("SELECT  * FROM " + TABLE_SALES, null);
  292.                 res.moveToFirst();
  293.                 while (!res.isAfterLast()) {
  294.                     SaleModel l_sales = new SaleModel();
  295.  
  296.                     l_sales.setId(res.getInt(res
  297.                             .getColumnIndex(KEY_SID)));
  298.                     l_sales.setTime_code(res.getString(res
  299.                             .getColumnIndex(KEY_TIME_CODE)));
  300.                     l_sales.setAttendant_id(res.getString(res
  301.                             .getColumnIndex(KEY_ATTENDANT_ID)));
  302.                     l_sales.setAttendant_name(res.getString(res
  303.                             .getColumnIndex(KEY_ATTENDANT_NAME)));
  304.                     l_sales.setProduct_id(res.getString(res
  305.                             .getColumnIndex(KEY_PRODUCT_ID)));
  306.                     l_sales.setPrice(res.getString(res
  307.                             .getColumnIndex(KEY_PRICE)));
  308.                     l_sales.setCustomer_id(res.getString(res
  309.                             .getColumnIndex(KEY_CUSTOMER_ID)));
  310.                     l_sales.setCustomer_first_name(res.getString(res
  311.                             .getColumnIndex(KEY_CUSTOMER_FIRST_NAME)));
  312.                     l_sales.setCustomer_last_name(res.getString(res
  313.                             .getColumnIndex(KEY_CUSTOMER_LAST_NAME)));
  314.                     l_sales.setCustomer_image(res.getString(res
  315.                             .getColumnIndex(KEY_CUSTOMER_IMAGE)));
  316.                     l_sales.setUid(res.getString(res
  317.                             .getColumnIndex(KEY_UID)));
  318.                     l_sales.setQuantity(res.getString(res
  319.                             .getColumnIndex(KEY_QUANTITY)));
  320.                     l_sales.setName(res.getString(res
  321.                             .getColumnIndex(KEY_PRODUCT_NAME)));
  322.                     l_sales.setImage(res.getString(res
  323.                             .getColumnIndex(KEY_PRODUCT_IMAGE)));
  324.                     l_sales.setCreated_at(res.getString(res
  325.                             .getColumnIndex(KEY_CREATED_AT)));
  326.                     l_sales.setSvg(res.getString(res
  327.                             .getColumnIndex(KEY_SVG)));
  328.                     l_sales.setOfflineTag(res.getString(res
  329.                             .getColumnIndex(KEY_OFFLINETAG)));
  330.                     l_sales.setQuantity_name(res.getString(res
  331.                             .getColumnIndex(KEY_QUANTITY)) + " " + res.getString(res
  332.                             .getColumnIndex(KEY_PRODUCT_NAME)));
  333.                     Log.d("my_products", res.getString(res
  334.                             .getColumnIndex(KEY_QUANTITY)) + " " + res.getString(res
  335.                             .getColumnIndex(KEY_PRODUCT_NAME)));
  336.  
  337.                     if (res.getString(res.getColumnIndex(KEY_DELETED_AT)).length() < 5) {
  338.  
  339.                         sales.add(l_sales);
  340.                     }
  341.  
  342.                     res.moveToNext();
  343.                 }
  344.                 res.close();
  345.                 Set<SaleModel> final_sales = new LinkedHashSet<SaleModel>(sales);
  346.                 final_sales.addAll(sales);
  347.                 sales.clear();
  348.                 sales.addAll(final_sales);
  349.                 Log.d(TAG, "Fetching sales from Sqlite: " + sales.toString());
  350.  
  351.             } catch (Exception e) {
  352.                 Log.d("addsale_exceptions1 ", e.toString());
  353.             } finally {
  354.                 if (db != null) {
  355.                     try {
  356.                         // db.close();
  357.                     } catch (Exception e) {
  358.                         Log.d("addsale_exceptions2", e.toString());
  359.                     }
  360.                 }
  361.                 endReadLock();
  362.             }
  363.         }
  364.         return sales;
  365.     }
  366.  
  367.     public ArrayList<SaleModel> displayFilteredSales() {
  368.         arraylist.clear();
  369.         ArrayList<SaleModel> sales = new ArrayList<>();
  370.         hp = new HashMap();
  371.         {
  372.             SQLiteDatabase db = null;
  373.  
  374.             try {
  375.                 beginReadLock();
  376.                 db = this.getWritableDatabase();
  377.                 Cursor res = db.rawQuery("SELECT  * FROM " + TABLE_SALES + " ORDER BY datetime(created_at) DESC", null);
  378.                 //Cursor res = db.rawQuery("SELECT  * FROM " + TABLE_SALES + " ORDER BY id ASC", null);
  379.                 //Cursor res = db.rawQuery("SELECT  * FROM " + TABLE_SALES, null);
  380.                 res.moveToFirst();
  381.                 while (!res.isAfterLast()) {
  382.                     SaleModel l_sales = new SaleModel();
  383.  
  384.                     l_sales.setId(res.getInt(res
  385.                             .getColumnIndex(KEY_SID)));
  386.                     l_sales.setTime_code(res.getString(res
  387.                             .getColumnIndex(KEY_TIME_CODE)));
  388.                     l_sales.setAttendant_id(res.getString(res
  389.                             .getColumnIndex(KEY_ATTENDANT_ID)));
  390.                     l_sales.setAttendant_name(res.getString(res
  391.                             .getColumnIndex(KEY_ATTENDANT_NAME)));
  392.                     l_sales.setProduct_id(res.getString(res
  393.                             .getColumnIndex(KEY_PRODUCT_ID)));
  394.                     l_sales.setPrice(res.getString(res
  395.                             .getColumnIndex(KEY_PRICE)));
  396.                     l_sales.setCustomer_id(res.getString(res
  397.                             .getColumnIndex(KEY_CUSTOMER_ID)));
  398.                     l_sales.setCustomer_first_name(res.getString(res
  399.                             .getColumnIndex(KEY_CUSTOMER_FIRST_NAME)));
  400.                     l_sales.setCustomer_last_name(res.getString(res
  401.                             .getColumnIndex(KEY_CUSTOMER_LAST_NAME)));
  402.                     l_sales.setCustomer_image(res.getString(res
  403.                             .getColumnIndex(KEY_CUSTOMER_IMAGE)));
  404.                     l_sales.setUid(res.getString(res
  405.                             .getColumnIndex(KEY_UID)));
  406.                     l_sales.setQuantity(res.getString(res
  407.                             .getColumnIndex(KEY_QUANTITY)));
  408.                     l_sales.setName(res.getString(res
  409.                             .getColumnIndex(KEY_PRODUCT_NAME)));
  410.                     l_sales.setImage(res.getString(res
  411.                             .getColumnIndex(KEY_PRODUCT_IMAGE)));
  412.                     l_sales.setCreated_at(res.getString(res
  413.                             .getColumnIndex(KEY_CREATED_AT)));
  414.                     l_sales.setSvg(res.getString(res
  415.                             .getColumnIndex(KEY_SVG)));
  416.                     l_sales.setOfflineTag(res.getString(res
  417.                             .getColumnIndex(KEY_OFFLINETAG)));
  418.                     l_sales.setQuantity_name(res.getString(res
  419.                             .getColumnIndex(KEY_QUANTITY)) + " " + res.getString(res
  420.                             .getColumnIndex(KEY_PRODUCT_NAME)));
  421.                     Log.d("my_products", res.getString(res
  422.                             .getColumnIndex(KEY_QUANTITY)) + " " + res.getString(res
  423.                             .getColumnIndex(KEY_PRODUCT_NAME)));
  424.                     if (res.getString(res.getColumnIndex(KEY_DELETED_AT)).length() < 5) {
  425.  
  426.                         if (getattid().equals(res.getString(res
  427.                                 .getColumnIndex(KEY_ATTENDANT_ID)))) {
  428.                             sales.add(l_sales);
  429.  
  430.                         }
  431.                     }
  432.                     res.moveToNext();
  433.                 }
  434.  
  435.                 Log.d(TAG, "Fetching sales from Sqlite: ");
  436.                 res.close();
  437.                 Set<SaleModel> final_sales = new LinkedHashSet<SaleModel>(sales);
  438.                 final_sales.addAll(sales);
  439.                 sales.clear();
  440.                 sales.addAll(final_sales);
  441.             } catch (Exception e) {
  442.                 Log.d("addsale_exceptions1 ", e.toString());
  443.             } finally {
  444.                 if (db != null) {
  445.                     try {
  446.                         // db.close();
  447.                     } catch (Exception e) {
  448.                         Log.d("addsale_exceptions2", e.toString());
  449.                     }
  450.                 }
  451.                 endReadLock();
  452.             }
  453.         }
  454.         return sales;
  455.     }
  456.  
  457.     public ArrayList<Entry> sales_values() {
  458.         hour_labels.clear();
  459.         Cursor c = null;
  460.         ArrayList<Entry> values = new ArrayList<>();
  461.         SQLiteDatabase db = this.getReadableDatabase();
  462.         if (set_variant.equals("price")) {
  463.             c = db.rawQuery("select created_at_am_pm ,sum(price) as sum \n" +
  464.                     "from loadSales\n" +
  465.                     "group by created_at_am_pm ", null);
  466.         } else {
  467.             c = db.rawQuery("select created_at_am_pm ,sum(quantity) as sum \n" +
  468.                     "from loadSales\n" +
  469.                     "group by created_at_am_pm ", null);
  470.         }
  471.         int i = 0;
  472.  
  473.         try {
  474.             while (c.moveToNext()) {
  475.                 Double sum = c.getDouble(1);
  476. //                int count = c.getCount();
  477. //                Log.d("Sum is: " + sum);
  478.  
  479.                 hour_labels.add(c.getString(c.getColumnIndex("created_at_am_pm")).replace("0", ""));
  480.                 values.add(new Entry(Float.valueOf(String.valueOf(sum)), i));
  481.  
  482.                 Log.d("sum_values_", String.valueOf(sum) + "/" + c.getString(c.getColumnIndex("created_at_am_pm")));
  483.                 i++;
  484.             }
  485.         } finally {
  486.             c.close();
  487.         }
  488.         Log.d("sum_values_values", values.size() + "/" + hour_labels.size());
  489.         return values;
  490.     }
  491.  
  492.     public ArrayList<Entry> products_values() {
  493.         Cursor c = null;
  494.         product_labels.clear();
  495.         ArrayList<Entry> values = new ArrayList<>();
  496.         SQLiteDatabase db = this.getReadableDatabase();
  497.         if (set_variant.equals("price")) {
  498.             c = db.rawQuery("select p_name ,sum(price) as sum \n" +
  499.                     "from loadSales\n" +
  500.                     "group by product_id ORDER BY sum(price) DESC LIMIT 20", null);
  501.         } else {
  502.             c = db.rawQuery("select p_name ,sum(quantity) as sum \n" +
  503.                     "from loadSales\n" +
  504.                     "group by product_id ORDER BY sum(quantity) DESC LIMIT 20", null);
  505.         }
  506.         int i = 0;
  507.         if (c != null) {
  508.  
  509.             try {
  510.                 while (c.moveToNext()) {
  511.                     Double sum = c.getDouble(1);
  512.  
  513.                     product_labels.add(mFormat.format(sum).replace(".0", "") + " " + c.getString(c.getColumnIndex("p_name")));
  514.                     values.add(new Entry(Float.valueOf(String.valueOf(sum)), i));
  515.  
  516.                     Log.d("sum_product_values_", String.valueOf(sum) + "/" + c.getString(c.getColumnIndex("p_name")));
  517.                     i++;
  518.                 }
  519.             } finally {
  520.                 c.close();
  521.             }
  522.         }
  523.         return values;
  524.     }
  525.  
  526.     public ArrayList<Entry> customer_values() {
  527.         customer_labels.clear();
  528.         ArrayList<Entry> values = new ArrayList<>();
  529.         Cursor c = null;
  530.         SQLiteDatabase db = this.getReadableDatabase();
  531.        /* Cursor c = db.rawQuery("select * ,sum(quantity) as sum \n" +
  532.                 "from loadSales\n" +
  533.                 "group by customer_id ORDER BY sum(quantity) DESC LIMIT 20", null);*/
  534.         if (set_variant.equals("price")) {
  535.             c = db.rawQuery("select customer_first_name,sum(price) as sum \n" +
  536.                     "from loadSales\n" +
  537.                     "group by customer_id ORDER BY sum DESC LIMIT 20", null);
  538.         } else {
  539.             c = db.rawQuery("select customer_first_name,sum(quantity) as sum \n" +
  540.                     "from loadSales\n" +
  541.                     "group by customer_id ORDER BY sum DESC LIMIT 20", null);
  542.         }
  543.         int i = 0;
  544.         if (c != null) {
  545.  
  546.             try {
  547.                 while (c.moveToNext()) {
  548.                     Double sum = c.getDouble(1);
  549.  
  550.                     customer_labels.add(mFormat.format(sum).replace(".0", "") + " " + c.getString(c.getColumnIndex("customer_first_name"))
  551.                            /* + " " + c.getString(c.getColumnIndex("customer_last_name"))*/);
  552.                     values.add(new Entry(Float.valueOf(String.valueOf(sum)), i));
  553.  
  554.                     Log.d("sum_customer_values_", String.valueOf(sum) + "/" + c.getString(c.getColumnIndex("customer_first_name")));
  555.                     i++;
  556.                 }
  557.             } finally {
  558.                 c.close();
  559.             }
  560.         }
  561. //        Log.d("sum_product_values_", values.size() + "/" + hour_labels.size());
  562.         return values;
  563.     }
  564.  
  565.     public ArrayList<Entry> staff_values() {
  566.         staff_labels.clear();
  567.         ArrayList<Entry> values = new ArrayList<>();
  568.         Cursor c = null;
  569.         SQLiteDatabase db = this.getReadableDatabase();
  570.         if (set_variant.equals("price")) {
  571.             c = db.rawQuery("select attendant_name,sum(price) as sum \n" +
  572.                     "from loadSales\n" +
  573.                     "group by attendant_id ORDER BY sum DESC", null);
  574.         } else {
  575.             c = db.rawQuery("select attendant_name,sum(quantity) as sum \n" +
  576.                     "from loadSales\n" +
  577.                     "group by attendant_id ORDER BY sum DESC", null);
  578.         }
  579.         int i = 0;
  580.  
  581.         if (c != null) {
  582.  
  583.             try {
  584.                 while (c.moveToNext()) {
  585.                     Double sum = c.getDouble(1);
  586.  
  587.                     staff_labels.add(mFormat.format(sum) + " " + c.getString(c.getColumnIndex("attendant_name"))
  588.                            /* + " " + c.getString(c.getColumnIndex("customer_last_name"))*/);
  589.                     values.add(new Entry(Float.valueOf(String.valueOf(sum)), i));
  590.  
  591.                     Log.d("sum_staff_values_", String.valueOf(sum) + "/" + c.getString(c.getColumnIndex("attendant_name")));
  592.                     i++;
  593.                 }
  594.             } finally {
  595.                 c.close();
  596.             }
  597.         }
  598. //        Log.d("sum_product_values_", values.size() + "/" + hour_labels.size());
  599.         return values;
  600.     }
  601.  
  602.     public String setVariant(String variant) {
  603.         set_variant = variant;
  604.         return variant;
  605.     }
  606.  
  607.     private String getTimeFormattedInAMPM(String dateStr) {
  608.         DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  609.         DateFormat writeFormat = new SimpleDateFormat("ha");
  610.         Date date = null;
  611.         try {
  612.             date = readFormat.parse(dateStr);
  613.         } catch (ParseException e) {
  614.             e.printStackTrace();
  615.         }
  616.         String formattedDate = writeFormat.format(date);
  617.         return formattedDate;
  618.     }
  619.  
  620.     public ArrayList<String> hour_labels() {
  621.         return hour_labels;
  622.     }
  623.  
  624.     public ArrayList<String> product_labels() {
  625.         return product_labels;
  626.     }
  627.  
  628.     public ArrayList<String> customer_labels() {
  629.         return customer_labels;
  630.     }
  631.  
  632.     public ArrayList<String> staff_labels() {
  633.         return staff_labels;
  634.     }
  635.  
  636.  
  637.     public double getFilteredTotalSales() {
  638.         SQLiteDatabase db = this.getReadableDatabase();
  639.         Cursor c = db.rawQuery("SELECT SUM(price) FROM " + TABLE_SALES + " WHERE "
  640.                 + KEY_ATTENDANT_ID + "= '" + getattid() + "' AND " + KEY_DELETED_AT + " IS ''", null);
  641.         c.moveToFirst();
  642.         double i = c.getDouble(0);
  643.         Log.d("double value database", String.valueOf(i));
  644.         c.close();
  645.         return i;
  646.     }
  647.  
  648.     String getattid() {
  649.         SharedPreferences spref2 = context.getSharedPreferences("ACCOUNT", context.MODE_PRIVATE);
  650.         String attid = spref2.getString("attid", "");
  651.         return attid;
  652.     }
  653.  
  654.     String getAdmin() {
  655.         SharedPreferences spref2 = context.getSharedPreferences("ACCOUNT", context.MODE_PRIVATE);
  656.         String admin = spref2.getString("admin", "");
  657.         return admin;
  658.     }
  659.  
  660.     public void deleteSingleSale(String sale_id) {
  661.         //Open the database
  662.         SQLiteDatabase database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  663.  
  664.         //Execute sql query to remove from database
  665.         //NOTE: When removing by String in SQL, value must be enclosed with ''
  666.         database.execSQL("DELETE FROM " + TABLE_SALES + " WHERE " + KEY_SID + "= '" + sale_id + "'");
  667.         Log.d("deleted_sale", sale_id + " from sqlite");
  668.         //Close the database
  669.         //causes SQLDatabaseLocked Exception
  670.         //database.close();
  671.     }
  672.  
  673.     public void deleteSingleSaleOnChildChanged(String time_code) {
  674.         //Open the database
  675.         SQLiteDatabase database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  676.  
  677.         //Execute sql query to remove from database
  678.         //NOTE: When removing by String in SQL, value must be enclosed with ''
  679.         database.execSQL("DELETE FROM " + TABLE_SALES + " WHERE " + KEY_TIME_CODE + "= '" + time_code + "'");
  680.         Log.d("deleted_sale", time_code + " from sqlite");
  681.         //Close the database
  682.         //causes SQLDatabaseLocked Exception
  683.         //database.close();
  684.     }
  685.  
  686.     public void deleteSingleSale(int sale_id) {
  687.         //Open the database
  688.         SQLiteDatabase database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  689.  
  690.         //Execute sql query to remove from database
  691.         //NOTE: When removing by String in SQL, value must be enclosed with ''
  692.         database.execSQL("DELETE FROM " + TABLE_SALES + " WHERE " + KEY_SID + "= '" + sale_id + "'");
  693.         Log.d("deleted_sale", sale_id + " from sqlite");
  694.         //Close the database
  695.         //causes SQLDatabaseLocked Exception
  696.         //database.close();
  697.     }
  698.  
  699.     public void deleteSales() {
  700.         SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  701.         // Delete All Rows
  702.         db.delete(TABLE_SALES, null, null);
  703.         // db.close();
  704.  
  705.         Log.d(TAG, "Deleted all user info from sqlite");
  706.     }
  707.  
  708.     public boolean checkForTables() {
  709.         boolean hasRows = false;
  710.         SQLiteDatabase db = getReadableDatabase();
  711.         Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_SALES, null);
  712.         cursor.moveToFirst();
  713.         int count = cursor.getInt(0);
  714.         if (count > 0)
  715.             hasRows = true;
  716.         cursor.close();
  717.         return hasRows;
  718.     }
  719.  
  720.     public int getRowCount() {
  721.         String countQuery = "SELECT  * FROM " + TABLE_SALES;
  722.         SQLiteDatabase db = this.getReadableDatabase();
  723.         Cursor cursor = db.rawQuery(countQuery, null);
  724.         int cnt = cursor.getCount();
  725.         // return row count
  726.         cursor.close();
  727.         return cnt;
  728.  
  729.     }
  730.  
  731.     public double getTotalSales() {
  732.         SQLiteDatabase db = this.getReadableDatabase();
  733.         Cursor c = db.rawQuery("SELECT SUM(price) FROM " + TABLE_SALES + " WHERE " + KEY_DELETED_AT + " IS ''", null);
  734.         c.moveToFirst();
  735.         double i = c.getDouble(0);
  736.         Log.d("double value database", String.valueOf(i));
  737.         c.close();
  738.         return i;
  739.     }
  740.  
  741.  
  742.     public void updateSingleSale(String s_id, String attendant_id, String
  743.             attendant_name, String product_id,
  744.                                  String price, String customer_id, String customer_first_name, String
  745.                                          customer_last_name,
  746.                                  String customer_image, String uid, String quantity, String p_name, String
  747.                                          p_image, String created_at,
  748.                                  String deleted_at, String svg, String offline_tag, String time_code) {
  749.         SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  750.  
  751.         Log.d("addsale_edited4", time_code);
  752.         ContentValues values = new ContentValues();
  753.  
  754.         values.put(KEY_SID, s_id);
  755.         values.put(KEY_TIME_CODE, time_code);
  756.         values.put(KEY_ATTENDANT_ID, attendant_id);
  757.         values.put(KEY_ATTENDANT_NAME, attendant_name);
  758.         values.put(KEY_PRODUCT_ID, product_id);
  759.         values.put(KEY_PRICE, price);  //price
  760.         values.put(KEY_CUSTOMER_ID, customer_id);
  761.         values.put(KEY_CUSTOMER_FIRST_NAME, customer_first_name);
  762.         values.put(KEY_CUSTOMER_LAST_NAME, customer_last_name);
  763.         values.put(KEY_CUSTOMER_IMAGE, customer_image);
  764.         values.put(KEY_UID, uid);
  765.         values.put(KEY_QUANTITY, quantity);
  766.         values.put(KEY_PRODUCT_NAME, p_name);
  767.         values.put(KEY_PRODUCT_IMAGE, p_image);
  768.         values.put(KEY_CREATED_AT, created_at);
  769.         values.put(KEY_DELETED_AT, deleted_at);
  770.         values.put(KEY_SVG, svg);
  771.         values.put(KEY_OFFLINETAG, offline_tag);
  772.         // Inserting Row
  773.         long id = db.update(TABLE_SALES, values, KEY_SID + "=" + s_id, null);
  774.         //myDataBase.update(TABLE, con, KEY_ID + "=" + id,null);
  775.         // mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null)>0;
  776.         // Closing database connection
  777.         Log.d("sale_id_edit", s_id);
  778.     }
  779.  
  780.     public String getLastSaleCreatedAtDate() {
  781.         String selectQuery = "SELECT * FROM " + TABLE_SALES + " ORDER BY id ASC LIMIT 1";
  782.         SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  783.         Cursor cursor = db.rawQuery(selectQuery, null);
  784.         String str = "0";
  785.         if (cursor.moveToFirst()) {
  786.             str = cursor.getString(cursor.getColumnIndex(KEY_CREATED_AT));
  787.         }
  788.         cursor.close();
  789.  
  790.         return str;
  791.     }
  792.  
  793.     /**
  794.      * MANY SALES+==================================================>
  795.      */
  796.     public void addToPendingSalesTable(String jsonProducts, String attendant_name, String
  797.             phone, String price, String customer_id, String attendant_id, String datetime, String timeCode, String status) {
  798.         SQLiteDatabase database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  799.         ContentValues values = new ContentValues();
  800.  
  801.         values.put(KEY_ATTENDANT_ID, attendant_id);
  802.         values.put(KEY_ATTENDANT_NAME, attendant_name);
  803.         values.put(KEY_CUSTOMER_ID, customer_id);
  804.         values.put(KEY_PRICE, price);
  805.         values.put(KEY_CREATED_AT, datetime);
  806.         values.put(KEY_TIME_CODE, timeCode);
  807.         values.put(KEY_PRODUCT_JSON, jsonProducts);
  808.         values.put(KEY_STATUS, status);
  809.         // values.put("updateStatus", "no");
  810.         long id = database.insert(TABLE_MANY_SALES, null, values);
  811.         // Closing database connection
  812.  
  813.         // database.endTransaction();
  814.         Log.d(TAG, "Offline checkout inserted into sqlite: " + "");
  815.     }
  816.  
  817.     public String composeSalesJSONfromSQLite() {
  818.         //convert sqlite rows into Json fields
  819.         Gson gson = new GsonBuilder().create();
  820.  
  821.         ArrayList<HashMap<String, Object>> offlineList = new ArrayList<>();
  822.         // here is what i'm talking about
  823.         // String product = "[{\"id\":\"2\",\"title\":\"bag\"}]";
  824.         String selectQuery = "SELECT  * FROM manySales ";
  825.         SQLiteDatabase database = this.getWritableDatabase();
  826.         Cursor cursor = database.rawQuery(selectQuery, null);
  827.         if (cursor.moveToFirst()) {
  828.  
  829.             do {
  830.                 Object[] productObj = gson.fromJson(cursor.getString(4), Object[].class);
  831.                 HashMap<String, Object> map = new HashMap<>();
  832.                 map.put("products", productObj);
  833.                 map.put("attendant_id", cursor.getString(1));
  834.                 map.put("attendant_name", cursor.getString(2));
  835.                 map.put("customer_id", cursor.getString(3));
  836.                 map.put("created_at", cursor.getString(5));
  837.                 map.put("price", cursor.getString(6));
  838.                 map.put("time_code", cursor.getString(9));
  839.                 //get sales that have pending status, to avoid duplication
  840.                 if (cursor.getString(8).equals("pending")) {
  841.                     offlineList.add(map);
  842.                 }
  843.             } while (cursor.moveToNext());
  844.         }
  845.         cursor.close();
  846.         // database.endTransaction();
  847.         System.out.println(gson.toJson(offlineList));
  848.         return gson.toJson(offlineList);
  849.     }
  850.  
  851.     public void updatePendingSalesToProcessing(String status) {
  852.         {
  853.             SQLiteDatabase db = null;
  854.  
  855.             try {
  856.                 beginWriteLock();
  857.                 db = this.getWritableDatabase();
  858.                 db.execSQL("UPDATE " + TABLE_MANY_SALES + " SET " + KEY_STATUS + " = '" + status + "'");
  859.                 Log.d("update_status", "updated pending sales to " + status);
  860.             } catch (Exception e) {
  861.                 Log.d("update_pending_e", e.toString());
  862.             } finally {
  863.                 if (db != null) {
  864.                     try {
  865.                         // db.close();
  866.                     } catch (Exception e) {
  867.                         Log.d("updatepending_e", e.toString());
  868.                     }
  869.                 }
  870.                 endWriteLock();
  871.             }
  872.  
  873.         }
  874.     }
  875.  
  876.     public void deletePendingSales() {
  877.         {
  878.             SQLiteDatabase db = null;
  879.  
  880.             try {
  881.                 beginWriteLock();
  882.                 db = this.getWritableDatabase();
  883.                 // Delete All Rows that have been processed
  884.                 // db.delete(TABLE_MANY_SALES, null, null);
  885.                 db.execSQL("DELETE FROM " + TABLE_MANY_SALES + " WHERE " + KEY_STATUS + " = 'processing'");
  886.  
  887.                 // db.close();
  888.                 //db.endTransaction();
  889.                 Log.d(TAG, "Deleted all user info from sqlite");
  890.             } catch (Exception e) {
  891.                 Log.d("addsale_exceptions1 ", e.toString());
  892.             } finally {
  893.                 if (db != null) {
  894.                     try {
  895.                         // db.close();
  896.                     } catch (Exception e) {
  897.                         Log.d("addsale_exceptions2", e.toString());
  898.                     }
  899.                 }
  900.                 endWriteLock();
  901.             }
  902.  
  903.         }
  904.     }
  905.  
  906.     public void deletePendingSingleSale(String time_code) {
  907.         //Open the database
  908.         SQLiteDatabase database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  909.  
  910.         //Execute sql query to remove from database
  911.         //NOTE: When removing by String in SQL, value must be enclosed with ''
  912.         database.execSQL("DELETE FROM " + TABLE_MANY_SALES + " WHERE " + KEY_TIME_CODE + "= '" + time_code + "'");
  913.         Log.d("deleted_sale", time_code + " from sqlite");
  914.         //Close the database
  915.         //causes SQLDatabaseLocked Exception
  916.         //database.close();
  917.     }
  918.  
  919.     public boolean checkForPendingSalesTables() {
  920.         boolean hasRows = false;
  921.         SQLiteDatabase db = getReadableDatabase();
  922.         Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_MANY_SALES, null);
  923.         cursor.moveToFirst();
  924.         int count = cursor.getInt(0);
  925.         if (count > 0)
  926.             hasRows = true;
  927.         cursor.close();
  928.         // db.endTransaction();
  929.         return hasRows;
  930.     }
  931.  
  932.     public int getFilteredTotalCountOfSales() {
  933.         {
  934.             SQLiteDatabase db = null;
  935.  
  936.             try {
  937.                 beginWriteLock();
  938.                 db = this.getWritableDatabase();
  939.                 db = this.getReadableDatabase();
  940.                 Cursor c = db.rawQuery("SELECT SUM(quantity) FROM " + TABLE_SALES + " WHERE "
  941.                         + KEY_ATTENDANT_ID + "= '" + getattid() + "'", null);
  942.                 c.moveToFirst();
  943.                 count = c.getInt(0);
  944.                 c.close();
  945.             } catch (Exception e) {
  946.                 Log.d("addsale_exceptions1 ", e.toString());
  947.             } finally {
  948.                 if (db != null) {
  949.                     try {
  950.                         // db.close();
  951.                     } catch (Exception e) {
  952.                         Log.d("addsale_exceptions2", e.toString());
  953.                     }
  954.                 }
  955.                 endWriteLock();
  956.             }
  957.  
  958.         }
  959.         return count;
  960.     }
  961.  
  962.     public int getTotalQuantityOfProducts() {
  963.         SQLiteDatabase db = this.getReadableDatabase();
  964.         Cursor c = db.rawQuery("SELECT SUM(quantity) FROM " + TABLE_SALES, null);
  965.         c.moveToFirst();
  966.         int i = c.getInt(0);
  967.         c.close();
  968.         return i;
  969.     }
  970.  
  971.     public void setLabelType(String label) {
  972.         period_label = label;
  973.     }
  974.  
  975.     /**
  976.      * TOTAL AMOUNT SALES+==================================================>
  977.      */
  978.     public void insertDateSelected(String created_at_am, String quantity,
  979.                                    String product_id, String name,
  980.                                    String customer_first_name,
  981.                                    String customer_last_name, String customer_id,
  982.                                    String attendant_name, String price, String attendant_id) {
  983.         SQLiteDatabase database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  984.         ContentValues values = new ContentValues();
  985.         values.put(KEY_CREATED_AT_AM_PM, getTimeFormattedInAMPM(created_at_am));
  986.         values.put(KEY_CREATED_AT_DAY, getDayFormatted(created_at_am));
  987.         values.put(KEY_CREATED_AT_MONTH, getMonthFormatted(created_at_am));
  988.         values.put(KEY_CREATED_AT_YEAR, getYearFormatted(created_at_am));
  989.         values.put(KEY_CREATED_AT, created_at_am);
  990.         values.put(KEY_QUANTITY, quantity);
  991.         values.put(KEY_COUNT, "1");
  992.         values.put(KEY_PRODUCT_ID, product_id);
  993.         values.put(KEY_PRODUCT_NAME, name);
  994.         values.put(KEY_CUSTOMER_FIRST_NAME, customer_first_name);
  995.         values.put(KEY_CUSTOMER_LAST_NAME, customer_last_name);
  996.         values.put(KEY_CUSTOMER_ID, customer_id);
  997.         values.put(KEY_ATTENDANT_ID, attendant_id);
  998.         values.put(KEY_PRICE, price);
  999.         values.put(KEY_ATTENDANT_NAME, attendant_name);
  1000.         long id = database.insert(TABLE_TOTAL_SALES, null, values);
  1001.         // Closing database connection
  1002.         Log.d(TAG, "total_checkout amount inserted into sqlite: " + id);
  1003.     }
  1004.  
  1005.     private String getDayFormatted(String dateStr) {
  1006.         DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1007.         DateFormat writeFormat = new SimpleDateFormat("dd");
  1008.         Date date = null;
  1009.         try {
  1010.             date = readFormat.parse(dateStr);
  1011.         } catch (ParseException e) {
  1012.             e.printStackTrace();
  1013.         }
  1014.         String formattedDate = writeFormat.format(date);
  1015.         return formattedDate;
  1016.     }
  1017.  
  1018.     private String getMonthFormatted(String dateStr) {
  1019.         DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1020.         DateFormat writeFormat = new SimpleDateFormat("MMM ");
  1021.         Date date = null;
  1022.         try {
  1023.             date = readFormat.parse(dateStr);
  1024.         } catch (ParseException e) {
  1025.             e.printStackTrace();
  1026.         }
  1027.         String formattedDate = writeFormat.format(date);
  1028.         return formattedDate;
  1029.     }
  1030.  
  1031.     private String getYearFormatted(String dateStr) {
  1032.         DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1033.         DateFormat writeFormat = new SimpleDateFormat("yyyy");
  1034.         Date date = null;
  1035.         try {
  1036.             date = readFormat.parse(dateStr);
  1037.         } catch (ParseException e) {
  1038.             e.printStackTrace();
  1039.         }
  1040.         String formattedDate = writeFormat.format(date);
  1041.         return formattedDate;
  1042.     }
  1043.  
  1044.     public double getTotalSalesAmount() {
  1045.         SQLiteDatabase db = this.getReadableDatabase();
  1046.         Cursor c = db.rawQuery("SELECT SUM(price) FROM " + TABLE_TOTAL_SALES, null);
  1047.         c.moveToFirst();
  1048.         double i = c.getDouble(0);
  1049.         Log.d("double value database", String.valueOf(i));
  1050.         c.close();
  1051.         return i;
  1052.     }
  1053.  
  1054.     public void deleteTotalSalesAmount() {
  1055.         SQLiteDatabase db = getReadableDatabase();
  1056.         // Delete All Rows
  1057.         db.delete(TABLE_TOTAL_SALES, null, null);
  1058.         // db.close();
  1059.  
  1060.         Log.d(TAG, "Deleted all TotalCheckousAmount");
  1061.     }
  1062.  
  1063.     public ArrayList<Entry> dateValues() {
  1064.         hour_labels.clear();
  1065.         ArrayList<Entry> values = new ArrayList<>();
  1066.         hour_labels().clear();
  1067.         SQLiteDatabase db = this.getReadableDatabase();
  1068.         Cursor c = null;
  1069.  
  1070.         if (period_label.equals("hours")) {
  1071.             c = db.rawQuery("select created_at_am_pm ,sum(count) as sum \n" +
  1072.                     "from total_sales\n" +
  1073.                     "group by created_at_am_pm  ORDER BY datetime(created_at_day) ASC ", null);
  1074.         }
  1075.         if (period_label.equals("days")) {
  1076.             c = db.rawQuery("select created_at_day ,sum(count) as sum \n" +
  1077.                     "from total_sales\n" +
  1078.                     "group by created_at_day ORDER BY datetime(created_at) ASC ", null);
  1079.         }
  1080.         if (period_label.equals("months")) {
  1081.             c = db.rawQuery("select created_at_month ,sum(count) as sum \n" +
  1082.                     "from total_sales\n" +
  1083.                     "group by created_at_month ORDER BY datetime(created_at) ASC ", null);
  1084.         }
  1085.  
  1086.         int i = 0;
  1087.  
  1088.         try {
  1089.             while (c.moveToNext()) {
  1090.                 Double sum = c.getDouble(1);
  1091. //                int count = c.getCount();
  1092. //                Log.d("Sum is: " + sum);
  1093.                 values.add(new Entry(Float.valueOf(String.valueOf(sum)), i));
  1094.                 Log.d("sum_values_entry", String.valueOf(sum));
  1095.                 if (period_label.equals("hours")) {
  1096.                     hour_labels.add(c.getString(c.getColumnIndex("created_at_am_pm")));
  1097.                 }
  1098.                 if (period_label.equals("days")) {
  1099.                     hour_labels.add(c.getString(c.getColumnIndex("created_at_day")));
  1100.                 }
  1101.                 if (period_label.equals("months")) {
  1102.                     hour_labels.add(c.getString(c.getColumnIndex("created_at_month")));
  1103.                 }
  1104.  
  1105. //                Log.d("sum_values_", String.valueOf(sum) + "/" + c.getString(c.getColumnIndex("created_at_am_pm")));
  1106.                 i++;
  1107.             }
  1108.         } finally {
  1109.             c.close();
  1110.         }
  1111.         Log.d("sum_sales_values", values.toString());
  1112.         Log.d("sum_sales_values", hour_labels.toString());
  1113.         Log.d("sum_sales_values", values.size() + "/" + hour_labels.size() + period_label);
  1114.         return values;
  1115.     }
  1116.  
  1117.     public ArrayList<Entry> date_products_values(String variant) {
  1118.         Cursor c = null;
  1119.         product_labels.clear();
  1120.         ArrayList<Entry> values = new ArrayList<>();
  1121.         SQLiteDatabase db = this.getReadableDatabase();
  1122.         c = db.rawQuery("select p_name ,sum('" + variant + "') as sum \n" +
  1123.                 "from total_sales\n" +
  1124.                 "group by product_id ORDER BY sum('" + variant + "') DESC", null);
  1125.         int i = 0;
  1126.         if (c != null) {
  1127.  
  1128.             try {
  1129.                 while (c.moveToNext()) {
  1130.                     Double sum = c.getDouble(1);
  1131.                     if (product_labels.size() < 10) {
  1132.                         product_labels.add(mFormat.format(sum).replace(".0", "") + " " + c.getString(c.getColumnIndex("p_name")));
  1133.                         values.add(new Entry(Float.valueOf(String.valueOf(sum)), i));
  1134.                     } else {
  1135.                         if (product_labels.contains("Others")) {
  1136.                             product_labels.add(mFormat.format(sum).replace(".0", "") + " Others");
  1137.                             values.add(new Entry(Float.valueOf(String.valueOf(sum)), i));
  1138.                         } else {
  1139.                             product_labels.add(mFormat.format(sum).replace(".0", "") + " Others");
  1140.                             values.add(new Entry(Float.valueOf(String.valueOf(sum)), i));
  1141.                         }
  1142.                     }
  1143.                     Log.d("sum_product_values_", String.valueOf(sum) + "/" + c.getString(c.getColumnIndex("p_name")));
  1144.                     i++;
  1145.                 }
  1146.             } finally {
  1147.                 c.close();
  1148.             }
  1149.         }
  1150.         return values;
  1151.     }
  1152.  
  1153.     public ArrayList<Entry> date_customer_values() {
  1154.         customer_labels.clear();
  1155.         ArrayList<Entry> values = new ArrayList<>();
  1156.         SQLiteDatabase db = this.getReadableDatabase();
  1157.        /* Cursor c = db.rawQuery("select * ,sum(quantity) as sum \n" +
  1158.                 "from total_sales\n" +
  1159.                 "group by customer_id ORDER BY sum(quantity) DESC LIMIT 20", null);*/
  1160.         Cursor c = db.rawQuery("select customer_first_name,sum(quantity) as sum \n" +
  1161.                 "from total_sales\n" +
  1162.                 "group by customer_id ORDER BY sum DESC LIMIT 20", null);
  1163.         int i = 0;
  1164.         if (c != null) {
  1165.  
  1166.             try {
  1167.                 while (c.moveToNext()) {
  1168.                     Double sum = c.getDouble(1);
  1169.  
  1170.                     customer_labels.add(String.valueOf(sum).replace(".0", "") + " " + c.getString(c.getColumnIndex("customer_first_name"))
  1171.                            /* + " " + c.getString(c.getColumnIndex("customer_last_name"))*/);
  1172.                     values.add(new Entry(Float.valueOf(String.valueOf(sum)), i));
  1173.  
  1174.                     Log.d("sum_customer_values_", c.getCount() + "/" +
  1175.                             String.valueOf(sum) + "/" + c.getString(c.getColumnIndex("customer_first_name")));
  1176.  
  1177.                     i++;
  1178.                 }
  1179.             } finally {
  1180.  
  1181.                 c.close();
  1182.             }
  1183.         }
  1184.  
  1185. //        Log.d("sum_product_values_", values.size() + "/" + hour_labels.size());
  1186.         return values;
  1187.     }
  1188.  
  1189.     public ArrayList<Entry> date_staff_values() {
  1190.         staff_labels.clear();
  1191.         ArrayList<Entry> values = new ArrayList<>();
  1192.  
  1193.         SQLiteDatabase db = this.getReadableDatabase();
  1194.         Cursor c = db.rawQuery("select attendant_name,sum(price) as sum \n" +
  1195.                 "from total_sales\n" +
  1196.                 "group by attendant_id ORDER BY sum DESC", null);
  1197.  
  1198.         int i = 0;
  1199.         if (c != null) {
  1200.  
  1201.             try {
  1202.                 while (c.moveToNext()) {
  1203.                     Double sum = c.getDouble(1);
  1204.  
  1205.                     staff_labels.add(String.valueOf(sum).replace(".0", "") + " " + c.getString(c.getColumnIndex("attendant_name"))
  1206.                            /* + " " + c.getString(c.getColumnIndex("customer_last_name"))*/);
  1207.                     values.add(new Entry(Float.valueOf(String.valueOf(sum)), i));
  1208.  
  1209.                     Log.d("sum_staff_values_", String.valueOf(sum) + "/" + c.getString(c.getColumnIndex("attendant_name")));
  1210.                     i++;
  1211.                 }
  1212.             } finally {
  1213.                 c.close();
  1214.             }
  1215.         }
  1216. //        Log.d("sum_product_values_", values.size() + "/" + hour_labels.size());
  1217.         return values;
  1218.     }
  1219.  
  1220.     /**
  1221.      * SALES TO DELETE+==================================================>
  1222.      */
  1223.  
  1224.     public void AddToDeleteSalesTable(String sale_id, int position) {
  1225.         SQLiteDatabase database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  1226.         ContentValues values = new ContentValues();
  1227.         values.put(KEY_SID, sale_id);
  1228.         values.put(KEY_POSITION, position);
  1229.         long id = database.insert(TABLE_DELETE_SALES, null, values);
  1230.         // Closing database connection
  1231.         Log.d(TAG, "sales to delete inserted into sqlite: " + id);
  1232.     }
  1233.  
  1234.     public void RemoveSaleFromDeleteTable(String sale_id) {
  1235.         //Open the database
  1236.         SQLiteDatabase database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  1237.         //Execute sql query to remove from database
  1238.         //NOTE: When removing by String in SQL, value must be enclosed with ''
  1239.         database.execSQL("DELETE FROM " + TABLE_DELETE_SALES + " WHERE " + KEY_SID + "= '" + sale_id + "'");
  1240.         Log.d("deleted_sale", sale_id + " from sqlite");
  1241.         //Close the database
  1242.         //causes SQLDatabaseLocked Exception
  1243.         //database.close();
  1244.     }
  1245.  
  1246.     public String getSaleIdToBeDeleted() {
  1247.         String selectQuery = "SELECT * FROM " + TABLE_DELETE_SALES + " ORDER BY s_id DESC LIMIT 1";
  1248.         SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  1249.         Cursor cursor = db.rawQuery(selectQuery, null);
  1250.         String str = "0";
  1251.         if (cursor.moveToFirst()) {
  1252.             str = cursor.getString(cursor.getColumnIndex(KEY_SID));
  1253.             pos = cursor.getInt(cursor.getColumnIndex(KEY_POSITION));
  1254.         }
  1255.         cursor.close();
  1256.         return str;
  1257.     }
  1258.  
  1259.     public int getPositionToBeDeleted() {
  1260.         return pos;
  1261.     }
  1262.  
  1263.     public void RemoveAllSalesToBeDeleted() {
  1264.         {
  1265.             SQLiteDatabase db = null;
  1266.  
  1267.             try {
  1268.                 beginWriteLock();
  1269.                 db = this.getWritableDatabase();
  1270.                 // Delete All Rows
  1271.                 db.delete(TABLE_DELETE_SALES, null, null);
  1272.                 // db.close();
  1273.                 //db.endTransaction();
  1274.                 Log.d(TAG, "Deleted all user info from sqlite");
  1275.             } catch (Exception e) {
  1276.                 Log.d("addsale_exceptions1 ", e.toString());
  1277.             } finally {
  1278.                 if (db != null) {
  1279.                     try {
  1280.                         // db.close();
  1281.                     } catch (Exception e) {
  1282.                         Log.d("addsale_exceptions2", e.toString());
  1283.                     }
  1284.                 }
  1285.                 endWriteLock();
  1286.             }
  1287.  
  1288.         }
  1289.     }
  1290.  
  1291.     public boolean checkForDeleteSalesQueueTables() {
  1292.         boolean hasRows = false;
  1293.         SQLiteDatabase db = getReadableDatabase();
  1294.         Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_DELETE_SALES, null);
  1295.         cursor.moveToFirst();
  1296.         int count = cursor.getInt(0);
  1297.         if (count > 0)
  1298.             hasRows = true;
  1299.         cursor.close();
  1300.         // db.endTransaction();
  1301.         return hasRows;
  1302.     }
  1303.  
  1304.     public String getAllSalesToBeDeleted() {
  1305.  
  1306.         ArrayList<Integer> saleIds = new ArrayList<Integer>();
  1307.         String selectQuery = "SELECT * FROM " + TABLE_DELETE_SALES;
  1308.         SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  1309.         Cursor cursor = db.rawQuery(selectQuery, null);
  1310.         int id = 0;
  1311.         if (cursor.moveToFirst()) {
  1312.  
  1313.             do {
  1314.                 id = cursor.getInt(cursor.getColumnIndex(KEY_SID));
  1315.                 saleIds.add(id);
  1316.             } while (cursor.moveToNext());
  1317.         }
  1318.  
  1319.         cursor.close();
  1320.         Gson gson = new Gson();
  1321.         return gson.toJson(saleIds);
  1322.     }
  1323.  
  1324.  
  1325.     /**
  1326.      * SALES KEYS TABLE+==================================================>
  1327.      */
  1328.  
  1329.     public void addSaleKey(String timeCode) {
  1330.         {
  1331.             SQLiteDatabase db = null;
  1332.  
  1333.             try {
  1334.                 beginWriteLock();
  1335.                 db = this.getWritableDatabase();
  1336.                 ContentValues values = new ContentValues();
  1337.                 values.put(KEY_TIME_CODE, timeCode);
  1338.                 // values.put("updateStatus", "no");
  1339.                 long id = db.insert(TABLE_SALES_KEYS, null, values);
  1340.                 // Closing database connection
  1341.  
  1342.                 // database.endTransaction()
  1343.             } catch (Exception e) {
  1344.                 Log.d("addsale_key ", e.toString());
  1345.             } finally {
  1346.                 if (db != null) {
  1347.                     try {
  1348.                         //db.close();
  1349.                     } catch (Exception e) {
  1350.                         Log.d("addsale_key", e.toString());
  1351.                     }
  1352.                 }
  1353.                 endWriteLock();
  1354.             }
  1355.  
  1356.         }
  1357.     }
  1358.  
  1359.     public Boolean isSaleKeyExisting(String sale_key) {
  1360.         SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
  1361.         String selectString = "SELECT * FROM " + TABLE_SALES_KEYS + " WHERE " + KEY_TIME_CODE + " =?";
  1362.         // Add the String you are searching by here.
  1363.         // Put it in an array to avoid an unrecognized token error
  1364.         Cursor cursor = db.rawQuery(selectString, new String[]{sale_key});
  1365.  
  1366.         boolean hasObject = false;
  1367.         if (cursor.moveToFirst()) {
  1368.             hasObject = true;
  1369.  
  1370.             //region if you had multiple records to check for, use this region.
  1371.  
  1372.             int count = 0;
  1373.             while (cursor.moveToNext()) {
  1374.                 count++;
  1375.             }
  1376.             //here, count is records found
  1377.             Log.d(TAG, String.format("%d records found", count));
  1378.  
  1379.             //endregion
  1380.  
  1381.         }
  1382.  
  1383.         cursor.close();          // Dont forget to close your cursor
  1384.         // db.close();              //AND your Database!
  1385.         return hasObject;
  1386.     }
  1387.  
  1388.     public void RemoveAllSalesKeys() {
  1389.         {
  1390.             SQLiteDatabase db = null;
  1391.  
  1392.             try {
  1393.                 beginWriteLock();
  1394.                 db = this.getWritableDatabase();
  1395.                 // Delete All Rows
  1396.                 db.delete(TABLE_SALES_KEYS, null, null);
  1397.                 // db.close();
  1398.                 //db.endTransaction();
  1399.                 Log.d(TAG, "Deleted all user info from sqlite");
  1400.             } catch (Exception e) {
  1401.                 Log.d("addsale_exceptions1 ", e.toString());
  1402.             } finally {
  1403.                 if (db != null) {
  1404.                     try {
  1405.                         // db.close();
  1406.                     } catch (Exception e) {
  1407.                         Log.d("addsale_exceptions2", e.toString());
  1408.                     }
  1409.                 }
  1410.                 endWriteLock();
  1411.             }
  1412.  
  1413.         }
  1414.     }
  1415.  
  1416.     public int getSaleKeysCount() {
  1417.         String countQuery = "SELECT  * FROM " + TABLE_SALES_KEYS;
  1418.         SQLiteDatabase db = this.getReadableDatabase();
  1419.         Cursor cursor = db.rawQuery(countQuery, null);
  1420.         int cnt = cursor.getCount();
  1421.         // return row count
  1422.         cursor.close();
  1423.         return cnt;
  1424.  
  1425.     }
  1426.  
  1427.     /**
  1428.      * NOTIFICATION SALES MESSAGES TABLE+==================================================>
  1429.      */
  1430.  
  1431.     public void addSalesNotifications(String message, String quantity) {
  1432.         {
  1433.             SQLiteDatabase db = null;
  1434.  
  1435.             try {
  1436.                 beginWriteLock();
  1437.                 db = this.getWritableDatabase();
  1438.                 ContentValues values = new ContentValues();
  1439.                 values.put(KEY_MESSAGE, message);
  1440.                 values.put(KEY_QUANTITY, quantity);
  1441.                 // values.put("updateStatus", "no");
  1442.                 long id = db.insert(TABLE_SALES_NOTIFICATIONS, null, values);
  1443.                 // Closing database connection
  1444.                 // database.endTransaction()
  1445.             } catch (Exception e) {
  1446.                 Log.d("addsale_key ", e.toString());
  1447.             } finally {
  1448.                 if (db != null) {
  1449.                     try {
  1450.                         // db.close();
  1451.                     } catch (Exception e) {
  1452.                         Log.d("addsale_key", e.toString());
  1453.                     }
  1454.                 }
  1455.                 endWriteLock();
  1456.             }
  1457.  
  1458.         }
  1459.     }
  1460.  
  1461.     public ArrayList<String> readLastNotifications() {
  1462.         {
  1463.             SQLiteDatabase db = null;
  1464.  
  1465.             try {
  1466.                 beginReadLock();
  1467.                 db = this.getWritableDatabase();
  1468.                 Cursor res = db.rawQuery("SELECT  * FROM " + TABLE_SALES_NOTIFICATIONS + " ORDER BY id ASC", null);
  1469.                 res.moveToFirst();
  1470.                 while (!res.isAfterLast()) {
  1471.                     String message = res.getString(res
  1472.                             .getColumnIndex(KEY_MESSAGE));
  1473.                     notificationsList.add(message);
  1474.                     res.moveToNext();
  1475.                 }
  1476.                 Log.d("notificat_sh", "sale-" + notificationsList.size());
  1477.  
  1478.                 Log.d(TAG, "Fetching promos from Sqlite: ");
  1479.                 res.close();
  1480.             } catch (Exception e) {
  1481.                 Log.d("readLastNotifications ", e.toString());
  1482.             } finally {
  1483.                 if (db != null) {
  1484.                     try {
  1485.                         // db.close();
  1486.                     } catch (Exception e) {
  1487.                         Log.d("readLastNotifications", e.toString());
  1488.                     }
  1489.                 }
  1490.                 endReadLock();
  1491.             }
  1492.  
  1493.         }
  1494.         return notificationsList;
  1495.     }
  1496.  
  1497.     public void RemoveAllNotificationMessages() {
  1498.         {
  1499.             SQLiteDatabase db = null;
  1500.  
  1501.             try {
  1502.                 beginWriteLock();
  1503.                 db = this.getWritableDatabase();
  1504.                 // Delete All Rows
  1505.                 db.delete(TABLE_SALES_NOTIFICATIONS, null, null);
  1506.                 // db.close();
  1507.                 //db.endTransaction();
  1508.                 Log.d(TAG, "Deleted all user info from sqlite");
  1509.             } catch (Exception e) {
  1510.                 Log.d("addsale_exceptions1 ", e.toString());
  1511.             } finally {
  1512.                 if (db != null) {
  1513.                     try {
  1514.                         // db.close();
  1515.                     } catch (Exception e) {
  1516.                         Log.d("addsale_exceptions2", e.toString());
  1517.                     }
  1518.                 }
  1519.                 endWriteLock();
  1520.             }
  1521.  
  1522.         }
  1523.     }
  1524.  
  1525.     public double getNotificationsCount() {
  1526.         SQLiteDatabase db = this.getReadableDatabase();
  1527.         Cursor c = db.rawQuery("SELECT SUM(quantity) FROM " + TABLE_SALES_NOTIFICATIONS, null);
  1528.         c.moveToFirst();
  1529.         double i = c.getDouble(0);
  1530.         Log.d("double value database", String.valueOf(i));
  1531.         c.close();
  1532.         return i;
  1533.     }
  1534.  
  1535. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement