Search in sources :

Example 1 with DateUtil

use of xyz.zedler.patrick.grocy.util.DateUtil in project grocy-android by patzly.

the class StockOverviewItemAdapter method onBindViewHolder.

@SuppressLint("ClickableViewAccessibility")
@Override
public void onBindViewHolder(@NonNull final ViewHolder viewHolder, int positionDoNotUse) {
    GroupedListItem groupedListItem = groupedListItems.get(viewHolder.getAdapterPosition());
    int type = getItemViewType(viewHolder.getAdapterPosition());
    if (type == GroupedListItem.TYPE_HEADER) {
        GroupViewHolder holder = (GroupViewHolder) viewHolder;
        if (((GroupHeader) groupedListItem).getDisplayDivider() == 1) {
            holder.binding.divider.setVisibility(View.VISIBLE);
        } else {
            holder.binding.divider.setVisibility(View.GONE);
        }
        holder.binding.name.setText(((GroupHeader) groupedListItem).getGroupName());
        return;
    }
    StockItem stockItem = (StockItem) groupedListItem;
    StockItemViewHolder holder = (StockItemViewHolder) viewHolder;
    // NAME
    holder.binding.textName.setText(stockItem.getProduct().getName());
    if (shoppingListItemsProductIds.contains(String.valueOf(stockItem.getProduct().getId())) && shoppingListFeatureEnabled) {
        holder.binding.viewOnShoppingList.setVisibility(View.VISIBLE);
    } else {
        holder.binding.viewOnShoppingList.setVisibility(View.GONE);
    }
    Context context = holder.binding.textAmount.getContext();
    // AMOUNT
    QuantityUnit quantityUnit = quantityUnitHashMap.get(stockItem.getProduct().getQuIdStockInt());
    holder.binding.textAmount.setText(AmountUtil.getStockAmountInfo(context, pluralUtil, stockItem, quantityUnit));
    if (missingItemsProductIds.contains(stockItem.getProductId())) {
        holder.binding.textAmount.setTypeface(ResourcesCompat.getFont(context, R.font.jost_medium));
        holder.binding.textAmount.setTextColor(ContextCompat.getColor(context, R.color.retro_blue_fg));
    } else {
        holder.binding.textAmount.setTypeface(ResourcesCompat.getFont(context, R.font.jost_book));
        holder.binding.textAmount.setTextColor(ContextCompat.getColor(context, R.color.on_background_secondary));
    }
    // BEST BEFORE
    String date = stockItem.getBestBeforeDate();
    String days = null;
    boolean colorDays = false;
    if (date != null) {
        days = String.valueOf(DateUtil.getDaysFromNow(date));
    }
    if (!showDateTracking) {
        holder.binding.linearDays.setVisibility(View.GONE);
    } else if (days != null && (sortMode.equals(FilterChipLiveDataStockSort.SORT_DUE_DATE) || Integer.parseInt(days) <= daysExpiringSoon && !date.equals(Constants.DATE.NEVER_OVERDUE))) {
        holder.binding.linearDays.setVisibility(View.VISIBLE);
        holder.binding.textDays.setText(new DateUtil(context).getHumanForDaysFromNow(date));
        if (Integer.parseInt(days) <= daysExpiringSoon) {
            colorDays = true;
        }
    } else {
        holder.binding.linearDays.setVisibility(View.GONE);
        holder.binding.textDays.setText(null);
    }
    if (colorDays) {
        holder.binding.textDays.setTypeface(ResourcesCompat.getFont(context, R.font.jost_medium));
        @ColorRes int color;
        if (Integer.parseInt(days) >= 0) {
            color = R.color.retro_yellow_fg;
        } else if (stockItem.getDueTypeInt() == StockItem.DUE_TYPE_BEST_BEFORE) {
            color = R.color.retro_dirt_fg;
        } else {
            color = R.color.retro_red_fg;
        }
        holder.binding.textDays.setTextColor(ContextCompat.getColor(context, color));
    } else {
        holder.binding.textDays.setTypeface(ResourcesCompat.getFont(context, R.font.jost_book));
        holder.binding.textDays.setTextColor(ContextCompat.getColor(context, R.color.on_background_secondary));
    }
    // CONTAINER
    holder.binding.linearContainer.setOnClickListener(view -> listener.onItemRowClicked(stockItem));
}
Also used : Context(android.content.Context) ColorRes(androidx.annotation.ColorRes) GroupedListItem(xyz.zedler.patrick.grocy.model.GroupedListItem) DateUtil(xyz.zedler.patrick.grocy.util.DateUtil) StockItem(xyz.zedler.patrick.grocy.model.StockItem) SuppressLint(android.annotation.SuppressLint) QuantityUnit(xyz.zedler.patrick.grocy.model.QuantityUnit) SuppressLint(android.annotation.SuppressLint)

Example 2 with DateUtil

use of xyz.zedler.patrick.grocy.util.DateUtil in project grocy-android by patzly.

the class ProductOverviewBottomSheet method loadPriceHistory.

private void loadPriceHistory() {
    if (!isFeatureEnabled(Constants.PREF.FEATURE_STOCK_PRICE_TRACKING)) {
        return;
    }
    dlHelper.get(activity.getGrocyApi().getPriceHistory(product.getId()), response -> {
        Type listType = new TypeToken<ArrayList<PriceHistoryEntry>>() {
        }.getType();
        ArrayList<PriceHistoryEntry> priceHistoryEntries;
        priceHistoryEntries = new Gson().fromJson(response, listType);
        if (priceHistoryEntries.isEmpty()) {
            return;
        }
        ArrayList<String> dates = new ArrayList<>();
        Collections.reverse(priceHistoryEntries);
        HashMap<String, ArrayList<BezierCurveChart.Point>> curveLists = new HashMap<>();
        for (PriceHistoryEntry priceHistoryEntry : priceHistoryEntries) {
            Store store = priceHistoryEntry.getStore();
            String storeName;
            if (store == null || store.getName().trim().isEmpty()) {
                storeName = activity.getString(R.string.property_store_unknown);
            } else {
                storeName = store.getName().trim();
            }
            if (!curveLists.containsKey(storeName)) {
                curveLists.put(storeName, new ArrayList<>());
            }
            ArrayList<BezierCurveChart.Point> curveList = curveLists.get(storeName);
            String date = new DateUtil(activity).getLocalizedDate(priceHistoryEntry.getDate(), DateUtil.FORMAT_SHORT);
            if (!dates.contains(date)) {
                dates.add(date);
            }
            assert curveList != null;
            curveList.add(new BezierCurveChart.Point(dates.indexOf(date), (float) priceHistoryEntry.getPrice()));
        }
        binding.itemPriceHistory.init(curveLists, dates);
        animateLinearPriceHistory();
    }, error -> {
    });
}
Also used : PriceHistoryEntry(xyz.zedler.patrick.grocy.model.PriceHistoryEntry) HashMap(java.util.HashMap) BezierCurveChart(xyz.zedler.patrick.grocy.view.BezierCurveChart) DateUtil(xyz.zedler.patrick.grocy.util.DateUtil) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) Store(xyz.zedler.patrick.grocy.model.Store) Type(java.lang.reflect.Type)

Example 3 with DateUtil

use of xyz.zedler.patrick.grocy.util.DateUtil in project grocy-android by patzly.

the class DateBottomSheet method onCreateView.

@SuppressLint("SimpleDateFormat")
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    binding = FragmentBottomsheetDateBinding.inflate(inflater, container, false);
    activity = (MainActivity) requireActivity();
    args = requireArguments();
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
    ;
    keyboardInputEnabled = sharedPrefs.getBoolean(BEHAVIOR.DATE_KEYBOARD_INPUT, SETTINGS_DEFAULT.BEHAVIOR.DATE_KEYBOARD_INPUT);
    boolean reverseDateFormat = sharedPrefs.getBoolean(BEHAVIOR.DATE_KEYBOARD_REVERSE, SETTINGS_DEFAULT.BEHAVIOR.DATE_KEYBOARD_REVERSE);
    calendar = Calendar.getInstance();
    dateUtil = new DateUtil(requireContext());
    dateFormatGrocy = new SimpleDateFormat("yyyy-MM-dd");
    if (reverseDateFormat) {
        dateFormatKeyboardInput = new SimpleDateFormat("ddMMyy");
        dateFormatKeyboardInputShort = new SimpleDateFormat("ddMM");
        binding.textInputDate.setHint("DDMM | DDMMYY");
    } else {
        dateFormatKeyboardInput = new SimpleDateFormat("yyMMdd");
        dateFormatKeyboardInputShort = new SimpleDateFormat("MMdd");
    }
    String selectedDate = args.getString(Constants.ARGUMENT.SELECTED_DATE);
    defaultDueDays = args.getString(Constants.ARGUMENT.DEFAULT_DAYS_FROM_NOW);
    binding.frameHelpButton.setOnClickListener(v -> {
        if (keyboardInputEnabled) {
            binding.helpKeyboard.setVisibility(View.VISIBLE);
        } else {
            binding.help.setVisibility(View.VISIBLE);
        }
    });
    binding.help.setOnClickListener(v -> navigateToSettingsCatBehavior());
    binding.helpKeyboard.setOnClickListener(v -> navigateToSettingsCatBehavior());
    if (keyboardInputEnabled) {
        binding.linearBodyPicker.setVisibility(View.GONE);
        binding.linearBodyKeyboard.setVisibility(View.VISIBLE);
        if (selectedDate == null || selectedDate.equals(DATE.NEVER_OVERDUE)) {
            binding.editTextDate.setText("");
        } else {
            try {
                Date date = dateFormatGrocy.parse(selectedDate);
                if (date != null) {
                    calendar.setTime(date);
                    binding.editTextDate.setText(dateFormatKeyboardInput.format(calendar.getTime()));
                } else {
                    binding.editTextDate.setText("");
                }
            } catch (ParseException e) {
                binding.editTextDate.setText("");
            }
        }
        if (savedInstanceState == null) {
            new Handler().postDelayed(() -> activity.showKeyboard(binding.editTextDate), 50);
        }
        updateDateHint();
        binding.editTextDate.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                updateDateHint();
            }
        });
        binding.editTextDate.setOnEditorActionListener((TextView v, int actionId, KeyEvent event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE && getTextFieldDate() != null) {
                dismiss();
                return true;
            }
            return false;
        });
        ActionButton moreMonth = reverseDateFormat ? binding.moreMonthReverse : binding.moreMonth;
        ActionButton lessMonth = reverseDateFormat ? binding.lessMonthReverse : binding.lessMonth;
        binding.linearMonth.setVisibility(reverseDateFormat ? View.GONE : View.VISIBLE);
        binding.linearMonthReverse.setVisibility(reverseDateFormat ? View.VISIBLE : View.GONE);
        moreMonth.setOnClickListener(view -> {
            Date date = getTextFieldDate();
            if (date != null) {
                String input = binding.editTextDate.getText() != null ? binding.editTextDate.getText().toString().trim() : "";
                calendar.setTime(date);
                calendar.add(Calendar.MONTH, 1);
                if (input.length() == 6) {
                    binding.editTextDate.setText(dateFormatKeyboardInput.format(calendar.getTime()));
                } else if (input.length() == 4) {
                    binding.editTextDate.setText(dateFormatKeyboardInputShort.format(calendar.getTime()));
                }
            }
        });
        binding.moreDay.setOnClickListener(view -> {
            Date date = getTextFieldDate();
            if (date != null) {
                String input = binding.editTextDate.getText() != null ? binding.editTextDate.getText().toString().trim() : "";
                calendar.setTime(date);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                if (input.length() == 6) {
                    binding.editTextDate.setText(dateFormatKeyboardInput.format(calendar.getTime()));
                } else if (input.length() == 4) {
                    binding.editTextDate.setText(dateFormatKeyboardInputShort.format(calendar.getTime()));
                }
            }
        });
        lessMonth.setOnClickListener(view -> {
            Date date = getTextFieldDate();
            if (date != null) {
                String input = binding.editTextDate.getText() != null ? binding.editTextDate.getText().toString().trim() : "";
                calendar.setTime(date);
                calendar.add(Calendar.MONTH, -1);
                if (input.length() == 6) {
                    binding.editTextDate.setText(dateFormatKeyboardInput.format(calendar.getTime()));
                } else if (input.length() == 4) {
                    binding.editTextDate.setText(dateFormatKeyboardInputShort.format(calendar.getTime()));
                }
            }
        });
        binding.lessDay.setOnClickListener(view -> {
            Date date = getTextFieldDate();
            if (date != null) {
                String input = binding.editTextDate.getText() != null ? binding.editTextDate.getText().toString().trim() : "";
                calendar.setTime(date);
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                if (input.length() == 6) {
                    binding.editTextDate.setText(dateFormatKeyboardInput.format(calendar.getTime()));
                } else if (input.length() == 4) {
                    binding.editTextDate.setText(dateFormatKeyboardInputShort.format(calendar.getTime()));
                }
            }
        });
        binding.clear.setOnClickListener(v -> {
            binding.editTextDate.setText("");
            activity.showKeyboard(binding.editTextDate);
        });
    } else {
        initDatePickerLayout();
        fillDatePickerForm(selectedDate);
    }
    setSkipCollapsedInPortrait();
    return binding.getRoot();
}
Also used : SharedPreferences(android.content.SharedPreferences) DateUtil(xyz.zedler.patrick.grocy.util.DateUtil) Handler(android.os.Handler) Date(java.util.Date) FormDataMasterProductCatDueDate(xyz.zedler.patrick.grocy.model.FormDataMasterProductCatDueDate) SuppressLint(android.annotation.SuppressLint) Paint(android.graphics.Paint) KeyEvent(android.view.KeyEvent) ActionButton(xyz.zedler.patrick.grocy.view.ActionButton) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) TextView(android.widget.TextView) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) SuppressLint(android.annotation.SuppressLint)

Example 4 with DateUtil

use of xyz.zedler.patrick.grocy.util.DateUtil in project grocy-android by patzly.

the class ProductOverviewBottomSheet method refreshItems.

private void refreshItems() {
    DateUtil dateUtil = new DateUtil(activity);
    // quantity unit refresh for an up-to-date value (productDetails has it in it)
    if (hasDetails()) {
        quantityUnit = productDetails.getQuantityUnitStock();
    }
    // AMOUNT
    StringBuilder amountNormal = new StringBuilder();
    StringBuilder amountAggregated = new StringBuilder();
    AmountUtil.addStockAmountNormalInfo(activity, pluralUtil, amountNormal, stockItem, quantityUnit);
    AmountUtil.addStockAmountAggregatedInfo(activity, pluralUtil, amountAggregated, stockItem, quantityUnit);
    binding.itemAmount.setText(activity.getString(R.string.property_amount), amountNormal.toString(), amountAggregated.toString().isEmpty() ? null : amountAggregated.toString().trim());
    binding.itemAmount.setSingleLine(false);
    // LOCATION
    if (hasDetails()) {
        // refresh
        location = productDetails.getLocation();
    }
    if (location != null && isFeatureEnabled(Constants.PREF.FEATURE_STOCK_LOCATION_TRACKING)) {
        binding.itemLocation.setText(activity.getString(R.string.property_location_default), location.getName(), null);
    } else {
        binding.itemLocation.setVisibility(View.GONE);
    }
    // BEST BEFORE
    if (isFeatureEnabled(Constants.PREF.FEATURE_STOCK_BBD_TRACKING)) {
        String bestBefore = stockItem.getBestBeforeDate();
        if (bestBefore == null) {
            // for "never" from dateUtil
            bestBefore = "";
        }
        binding.itemDueDate.setText(activity.getString(R.string.property_due_date_next), !bestBefore.equals(Constants.DATE.NEVER_OVERDUE) ? dateUtil.getLocalizedDate(bestBefore) : activity.getString(R.string.date_never), !bestBefore.equals(Constants.DATE.NEVER_OVERDUE) && !bestBefore.isEmpty() ? dateUtil.getHumanForDaysFromNow(bestBefore) : null);
    }
    if (hasDetails()) {
        // LAST PURCHASED
        String lastPurchased = productDetails.getLastPurchased();
        binding.itemLastPurchased.setText(activity.getString(R.string.property_last_purchased), lastPurchased != null ? dateUtil.getLocalizedDate(lastPurchased) : activity.getString(R.string.date_never), lastPurchased != null ? dateUtil.getHumanForDaysFromNow(lastPurchased) : null);
        // LAST USED
        String lastUsed = productDetails.getLastUsed();
        binding.itemLastUsed.setText(activity.getString(R.string.property_last_used), lastUsed != null ? dateUtil.getLocalizedDate(lastUsed) : activity.getString(R.string.date_never), lastUsed != null ? dateUtil.getHumanForDaysFromNow(lastUsed) : null);
        // LAST PRICE
        String lastPrice = productDetails.getLastPrice();
        if (NumUtil.isStringDouble(lastPrice) && isFeatureEnabled(Constants.PREF.FEATURE_STOCK_PRICE_TRACKING)) {
            binding.itemLastPrice.setText(activity.getString(R.string.property_last_price), NumUtil.trimPrice(Double.parseDouble(lastPrice)) + " " + sharedPrefs.getString(Constants.PREF.CURRENCY, ""), null);
        }
        // SHELF LIFE
        int shelfLife = productDetails.getAverageShelfLifeDaysInt();
        if (shelfLife != 0 && shelfLife != -1 && isFeatureEnabled(Constants.PREF.FEATURE_STOCK_BBD_TRACKING)) {
            binding.itemShelfLife.setText(activity.getString(R.string.property_average_shelf_life), dateUtil.getHumanDuration(shelfLife), null);
        }
        // SPOIL RATE
        binding.itemSpoilRate.setText(activity.getString(R.string.property_spoil_rate), NumUtil.trim(productDetails.getSpoilRatePercent()) + "%", null);
    }
}
Also used : DateUtil(xyz.zedler.patrick.grocy.util.DateUtil)

Aggregations

DateUtil (xyz.zedler.patrick.grocy.util.DateUtil)4 SuppressLint (android.annotation.SuppressLint)2 Context (android.content.Context)1 SharedPreferences (android.content.SharedPreferences)1 Paint (android.graphics.Paint)1 Handler (android.os.Handler)1 Editable (android.text.Editable)1 TextWatcher (android.text.TextWatcher)1 KeyEvent (android.view.KeyEvent)1 TextView (android.widget.TextView)1 ColorRes (androidx.annotation.ColorRes)1 Gson (com.google.gson.Gson)1 Type (java.lang.reflect.Type)1 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 FormDataMasterProductCatDueDate (xyz.zedler.patrick.grocy.model.FormDataMasterProductCatDueDate)1 GroupedListItem (xyz.zedler.patrick.grocy.model.GroupedListItem)1