ZaharL
11/11/2019 - 1:58 PM

AddProductActivity

package com.leaditteam.edaregion.ui.activity.add_product;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.widget.TextView;

import com.arellomobile.mvp.MvpAppCompatActivity;
import com.arellomobile.mvp.presenter.InjectPresenter;
import com.crashlytics.android.Crashlytics;
import com.leaditteam.edaregion.AppConstants;
import com.leaditteam.edaregion.R;
import com.leaditteam.edaregion.di.add_product.AddProductComponent;
import com.leaditteam.edaregion.di.add_product.AddProductModule;
import com.leaditteam.edaregion.di.add_product.DaggerAddProductComponent;
import com.leaditteam.edaregion.model.database.dao.Price;
import com.leaditteam.edaregion.model.database.dao.Product;
import com.leaditteam.edaregion.model.pojos.DocumentItem;
import com.leaditteam.edaregion.model.pojos.OutletItem;
import com.leaditteam.edaregion.presentation.presenter.add_product.AddProductPresenter;
import com.leaditteam.edaregion.presentation.view.add_product.AddProductView;
import com.leaditteam.edaregion.ui.adapter.add_product.ManufacturersAdapter;
import com.leaditteam.edaregion.ui.adapter.add_product.ProductAdapter;
import com.leaditteam.edaregion.ui.dialog.TextDialogProvider;

import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import timber.log.Timber;

public class AddProductActivity extends MvpAppCompatActivity implements AddProductView {
    @BindView(R.id.add_product_tv_manufacturer_name)
    AppCompatAutoCompleteTextView manufacturerName;
    @BindView(R.id.add_product_tv_product_name)
    AppCompatAutoCompleteTextView productName;
    @BindView(R.id.add_product_tv_quantity)
    AppCompatAutoCompleteTextView quantity;
    @BindView(R.id.add_product_tv_price)
    TextView price;
    @BindView(R.id.add_product_tv_sum)
    TextView sum;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;

    @InjectPresenter
    AddProductPresenter presenter;

    @Inject
    ManufacturersAdapter manufacturersAdapter;
    @Inject
    ProductAdapter productAdapter;

    private String productType;
    private String clientCode;
    private String outletCode;
    private String manufacturerId;

    private Product product;

    private Unbinder unbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_product);
        unbinder = ButterKnife.bind(this);
        attachUI();
        extractExtras();
    }

    private void attachUI() {
        initDI();
        initToolbar();
        initAutoComplete();
    }

    private void initDI() {

        AddProductComponent component = DaggerAddProductComponent.builder()
                .addProductModule(new AddProductModule(this))
                .build();
        component.inject(this);
    }

    private void initToolbar() {
        toolbarTitle.setText(R.string.add_product);
        setSupportActionBar(toolbar);
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayHomeAsUpEnabled(true);
            supportActionBar.setDisplayShowTitleEnabled(false);
        }
    }

    private void extractExtras() {
        Intent intent = getIntent();
        String productType = intent.getStringExtra(AppConstants.EXTRA_PRODUCT_TYPE);
        outletCode = intent.getStringExtra(AppConstants.EXTRA_OUTLET_CODE);
        clientCode = intent.getStringExtra(AppConstants.EXTRA_CLIENT_CODE);
        if (productType != null && outletCode != null && clientCode != null) {
            this.productType = productType;
            presenter.setExtraData(productType, clientCode);
        }
    }

    private void initAutoComplete() {
        presenter.setManufacturersAdapter(manufacturersAdapter);
        presenter.setProductAdapter(productAdapter);
        manufacturerName.setAdapter(manufacturersAdapter);
        manufacturerName.setOnItemClickListener((parent, view, position, id) -> {
            manufacturerId = manufacturersAdapter.getManufacturerId(position);
            presenter.fillProductsAutoCompletion(manufacturerId);
        });
        manufacturerName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().equals("")) {
                    productName.setText("");
                    clearWindowData();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        productName.setAdapter(productAdapter);
        productName.setOnItemClickListener((parent, view, position, id) -> {
            product = productAdapter.getProduct(position);
            setPriceAndSum(0);
        });
        productName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().equals("")) {
                    clearWindowData();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        quantity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String string = s.toString();
                if (!string.equals("")) {
                    try {
                        setPriceAndSum(Double.parseDouble(string));
                    } catch (NumberFormatException e) {
                        setPriceAndSum(0);
                    }
                } else {
                    setPriceAndSum(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void setPriceAndSum(double quant) {
        Price productPrice;
        if (product != null) {
            List<Price> prices = product.getPrices();
            if (!prices.isEmpty()) {
                productPrice = prices.get(0);
                price.setText(String.valueOf(productPrice.getValue()));
                sum.setText(String.format(Locale.getDefault(), "%.3f",
                        productPrice.getValue() * quant));
            }
        }
    }

    private void clearWindowData() {
        product = null;
        quantity.setText("");
        price.setText("");
        sum.setText("");
    }

    @OnClick(R.id.add_product_btn)
    void addProduct() {
        if (!checkForInput() || product == null) return;
        double price = 0d;
        double quantity = 0d;
        try {
            price = Double.parseDouble(this.price.getText().toString());
            quantity = Double.parseDouble(this.quantity.getText().toString());
        } catch (NumberFormatException e) {
            Timber.e(e);
        }
        DocumentItem lo = new DocumentItem();
        lo.setProductCode(product.getCode());
        lo.setClient_code(clientCode);
        lo.setOutlet_code(outletCode);
        lo.setImgSmall(product.getImg_small_src());
        lo.setImgBig(product.getImg_big_src());
        lo.setImgLocal(product.getImg_local_path());
        lo.setManufacturer_id(manufacturerId);
        lo.setManufacturer_name(manufacturerName.getText().toString());
        lo.setName(productName.getText().toString());
        lo.setPrice(this.price.getText().toString());
        lo.setQuantity(this.quantity.getText().toString());
        double sum = price * quantity;
        double weight = quantity * Double.parseDouble(product.getWeight());
        if (productType.equals(OutletItem.TYPE_RETURN)){
            sum = -sum;
            weight = -weight;
        }
        lo.setSumToUpdate(sum);
        try {
            lo.setWeightToUpdate(weight);
        } catch (NumberFormatException e) {
            Crashlytics.log(e.getLocalizedMessage());
        }
        presenter.addProduct(lo);
        setResult(RESULT_OK);
        finish();
    }

    private boolean checkForInput() {
        if (manufacturerName.getText().toString().equals("")) {
            manufacturerName.setError(getString(R.string.choose_manufacturer));
            return false;
        }
        if (productName.getText().toString().equals("")) {
            productName.setError(getString(R.string.choose_product));
            return false;
        }
        if (quantity.getText().toString().equals("")) {
            quantity.setError(getString(R.string.input_quantity));
            return false;
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            new TextDialogProvider(this, getString(R.string.exit),
                    getString(R.string.dismiss),
                    getString(R.string.exit_content))
                    .show((dialog, which) -> finish());
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activity.add_product.AddProductActivity">

    <include
        android:id="@+id/local_toolbar"
        layout="@layout/toolbar" />

    <android.support.v7.widget.AppCompatAutoCompleteTextView
        android:id="@+id/add_product_tv_manufacturer_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="18dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="18dp"
        android:background="@drawable/background_edittext"
        android:completionThreshold="1"
        android:hint="@string/manufacturer_name"
        android:imeOptions="actionNext"
        android:inputType="textAutoComplete"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/local_toolbar"/>

    <android.support.v7.widget.AppCompatAutoCompleteTextView
        android:id="@+id/add_product_tv_product_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="18dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="18dp"
        android:background="@drawable/background_edittext"
        android:completionThreshold="1"
        android:hint="@string/product_name"
        android:imeOptions="actionNext"
        android:inputType="textAutoComplete"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/add_product_tv_manufacturer_name" />

    <android.support.v7.widget.AppCompatAutoCompleteTextView
        android:id="@+id/add_product_tv_quantity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="18dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="18dp"
        android:background="@drawable/background_edittext"
        android:completionThreshold="1"
        android:digits="0123456789."
        android:hint="@string/quantity"
        android:imeOptions="actionDone"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/add_product_tv_product_name" />

    <TextView
        android:id="@+id/add_product_label_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="@string/price"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/add_product_tv_quantity" />

    <TextView
        android:id="@+id/add_product_tv_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="16dp"
        app:layout_constraintStart_toEndOf="@+id/add_product_label_price"
        app:layout_constraintTop_toBottomOf="@+id/add_product_tv_quantity" />

    <TextView
        android:id="@+id/add_product_label_sum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:text="@string/pay_sum"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/add_product_label_price" />

    <TextView
        android:id="@+id/add_product_tv_sum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toEndOf="@+id/add_product_label_sum"
        app:layout_constraintTop_toBottomOf="@+id/add_product_tv_price" />

    <Button
        android:id="@+id/add_product_btn"
        style="@style/Button.Blue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="24dp"
        android:minHeight="0dp"
        android:paddingLeft="24dp"
        android:paddingTop="8dp"
        android:paddingRight="24dp"
        android:paddingBottom="8dp"
        android:text="@string/add"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>
package com.leaditteam.edaregion.presentation.presenter.add_product;

import com.arellomobile.mvp.InjectViewState;
import com.arellomobile.mvp.MvpPresenter;
import com.leaditteam.edaregion.App;
import com.leaditteam.edaregion.model.database.DatabaseLayer;
import com.leaditteam.edaregion.model.database.dao.Manufacturer;
import com.leaditteam.edaregion.model.database.dao.Product;
import com.leaditteam.edaregion.model.pojos.DocumentItem;
import com.leaditteam.edaregion.model.pojos.OutletItem;
import com.leaditteam.edaregion.presentation.view.add_product.AddProductView;
import com.leaditteam.edaregion.ui.adapter.add_product.ManufacturersAdapter;
import com.leaditteam.edaregion.ui.adapter.add_product.ProductAdapter;

import java.util.List;

import javax.inject.Inject;

import timber.log.Timber;

@InjectViewState
public class AddProductPresenter extends MvpPresenter<AddProductView> {

    @Inject
    DatabaseLayer databaseLayer;

    private ManufacturersAdapter manufacturersAdapter;
    private ProductAdapter productAdapter;
    private String productType;
    private String clientCode;

    public AddProductPresenter() {
        App.getComponent().inject(this);
    }

    public void setManufacturersAdapter(ManufacturersAdapter manufacturersAdapter) {
        this.manufacturersAdapter = manufacturersAdapter;
        getCompletionData();
    }

    public void setProductAdapter(ProductAdapter productAdapter) {
        this.productAdapter = productAdapter;
    }

    private void getCompletionData() {
        List<Manufacturer> manufacturers = databaseLayer.getManufacturers();
        manufacturersAdapter.setManufacturers(manufacturers);
    }

    public void fillProductsAutoCompletion(String manufacturerId) {
        List<Product> products = databaseLayer.getProducts(manufacturerId, clientCode);
        if (products != null) {
            productAdapter.setProducts(products);
        } else {
            Timber.e("Products for this manufacturer id" + manufacturerId + "and client code " + clientCode + " not found!");
        }
    }

    public void setExtraData(String productType, String clientCode) {
        this.productType = productType;
        this.clientCode = clientCode;
    }

    public void addProduct(DocumentItem lo) {
        if (productType.equals(OutletItem.TYPE_REALISATION)) {
            databaseLayer.updateOrderQuantity(lo);
            databaseLayer.setRealisationUpdated(lo.getOutlet_code(), lo.getClient_code(), true);
        } else if (productType.equals(OutletItem.TYPE_RETURN)) {
            databaseLayer.updateReturnQuantity(lo);
            databaseLayer.setReturnUpdated(lo.getOutlet_code(), lo.getClient_code(), true);
        }
    }
}