Commit eff6598d authored by Daniel Cesanelli's avatar Daniel Cesanelli
Browse files

Agragado final de compra

parent 8bb419a0
......@@ -20,6 +20,7 @@ import androidx.navigation.ui.NavigationUI;
import com.cesanelli.lajusta.io.ApiAdapter;
import com.cesanelli.lajusta.io.models.Token;
import com.cesanelli.lajusta.io.models.User;
import com.cesanelli.lajusta.ui.viewmodel.CartViewModel;
import com.cesanelli.lajusta.ui.viewmodel.UserViewModel;
import com.google.android.material.navigation.NavigationView;
......@@ -88,6 +89,7 @@ public class MainActivity extends AppCompatActivity {
Token token = new Token();
try {
if (response.isSuccessful()) {
token.setValue(jwt);
token.setUser(response.body());
} else {
......
......@@ -23,7 +23,8 @@ public class ApiAdapter {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
String baseUrl = "http://ec2-3-235-40-183.compute-1.amazonaws.com/api/";
// String baseUrl = "http://ec2-3-235-40-183.compute-1.amazonaws.com/api/";
String baseUrl = "http://ec2-3-236-129-11.compute-1.amazonaws.com:8080/api/";
if (API_SERVICE == null) {
ObjectMapper objectMapper = new ObjectMapper();
......
......@@ -8,6 +8,7 @@ public class Cart {
private Integer quantity;
private float total;
private ActiveNode nodeDate;
private User user;
public Cart() {
cartProducts = new ArrayList<CartItem>();
......@@ -48,4 +49,28 @@ public class Cart {
public void setNode(ActiveNode node) {
this.nodeDate = node;
}
public boolean isCanceled() {
return isCanceled;
}
public void setCanceled(boolean canceled) {
isCanceled = canceled;
}
public ActiveNode getNodeDate() {
return nodeDate;
}
public void setNodeDate(ActiveNode nodeDate) {
this.nodeDate = nodeDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
......@@ -9,6 +9,9 @@ public class CartItem {
this.quantity = quantity;
}
public CartItem() {
}
public Product getProduct() {
return product;
}
......
......@@ -2,11 +2,14 @@ package com.cesanelli.lajusta.io.models;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.util.Base64;
import android.widget.ImageView;
import androidx.databinding.BindingAdapter;
import com.cesanelli.lajusta.R;
public class Product {
private int id;
private String title;
......@@ -16,8 +19,7 @@ public class Product {
private boolean isPromotion;
private Category[] categories;
private Image[] images;
private Unit unit;
private int unitQuantity;
private int stock;
public int getId() {
return id;
......@@ -83,20 +85,12 @@ public class Product {
this.images = images;
}
public Unit getUnit() {
return unit;
}
public void setUnit(Unit unit) {
this.unit = unit;
}
public int getUnitQuantity() {
return unitQuantity;
public int getStock() {
return stock;
}
public void setUnitQuantity(int unitQuantity) {
this.unitQuantity = unitQuantity;
public void setStock(int stock) {
this.stock = stock;
}
@BindingAdapter("android:productImage")
......@@ -106,6 +100,9 @@ public class Product {
byte[] decodedString = Base64.decode(cleanImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);
} else {
imageView.setImageResource(R.drawable.ic_baseline_image_24);
imageView.setColorFilter( 0xffcccccc, PorterDuff.Mode.MULTIPLY );
}
}
......
package com.cesanelli.lajusta.ui;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
......@@ -18,16 +17,9 @@ import androidx.recyclerview.widget.RecyclerView;
import com.cesanelli.lajusta.R;
import com.cesanelli.lajusta.databinding.FragmentCartListBinding;
import com.cesanelli.lajusta.io.ApiAdapter;
import com.cesanelli.lajusta.io.models.Cart;
import com.cesanelli.lajusta.io.models.CartItem;
import com.cesanelli.lajusta.io.models.User;
import com.cesanelli.lajusta.ui.viewmodel.CartViewModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CartFragment extends Fragment implements CartRecyclerViewAdapter.OnCartListener {
private FragmentCartListBinding fragmentCartListBinding;
private CartViewModel cartViewModel;
......@@ -66,6 +58,7 @@ public class CartFragment extends Fragment implements CartRecyclerViewAdapter.On
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(new CartRecyclerViewAdapter(cart, this));
fragmentCartListBinding.setCart(cart);
btnComprar.setEnabled(cart.getTotal() > 0);
}
});
......@@ -81,12 +74,15 @@ public class CartFragment extends Fragment implements CartRecyclerViewAdapter.On
public void onProductRemove(CartItem cartItem) {
cartViewModel.deleteProduct(cartItem.getProduct().getId());
Toast.makeText(getContext(), "Se eliminó " + cartItem.getProduct().getTitle() + " al carrito.", Toast.LENGTH_SHORT).show();
}
@Override
public void onAddQuantity(CartItem cartItem) {
cartViewModel.addQuantity(cartItem.getProduct().getId());
if (cartItem.getQuantity() < cartItem.getProduct().getStock()) {
cartViewModel.addQuantity(cartItem.getProduct().getId());
} else {
Toast.makeText(getContext(), "No hay stock suficiente.", Toast.LENGTH_LONG).show();
}
}
@Override
......
......@@ -78,21 +78,23 @@ public class LoginFragment extends Fragment {
sharedpreferences.edit().putString("UserID", Integer.toString(token.getUser().getId())).apply();
UserViewModel userViewModel = new ViewModelProvider(getActivity()).get(UserViewModel.class);
userViewModel.setToken(token);
Toast.makeText(getContext(), "¡Bienvenido " + token.getUser().getFirstName() + "!", Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(), "¡Bienvenido " + token.getUser().getFirstName() + "!", Toast.LENGTH_LONG).show();
Navigation.findNavController(v).navigate(R.id.nav_products);
} else {
Toast.makeText(getContext(), "Usuario o password incorrectos.", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
System.out.println(ex.getMessage());
Toast.makeText(getContext(), "Error en login. Por favor intente nuevamente.", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Token> call, Throwable t) {
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
System.out.println(t.getMessage());
Toast.makeText(getContext(), "Error en login. Por favor intente nuevamente.", Toast.LENGTH_LONG).show();
}
});
//Navigation.findNavController(v).navigate(R.id.nav_cars);
}
});
......
......@@ -91,8 +91,12 @@ public class ProductsFragment extends Fragment implements ProductsRecyclerViewAd
@Override
public void onProductAdd(Product product) {
cartViewModel.addProduct(product);
Toast.makeText(getContext(), "Se agregó " + product.getTitle() + " al carrito.", Toast.LENGTH_SHORT).show();
if(product.getStock()>0){
cartViewModel.addProduct(product);
Toast.makeText(getContext(), "Se agregó " + product.getTitle() + " al carrito.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Producto sin stock.", Toast.LENGTH_LONG).show();
}
}
@Override
......
package com.cesanelli.lajusta.ui;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import com.cesanelli.lajusta.R;
import com.cesanelli.lajusta.io.models.Cart;
import com.cesanelli.lajusta.ui.viewmodel.CartViewModel;
public class PurchaseFinalFragment extends Fragment {
private CartViewModel cartViewModel;
public PurchaseFinalFragment() {
// Required empty public constructor
}
public static PurchaseFinalFragment newInstance(String param1, String param2) {
PurchaseFinalFragment fragment = new PurchaseFinalFragment();
return fragment;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnSeguirComprando = view.findViewById(R.id.btnSeguirComprando);
String jwt = PreferenceManager.getDefaultSharedPreferences(getContext()).getString("JWT", "");
cartViewModel = new ViewModelProvider(getActivity()).get(CartViewModel.class);
Cart cart = cartViewModel.getCart().getValue();
if (cart != null && cart.getNode() != null) {
TextView txtDescription = view.findViewById(R.id.txtDescription);
StringBuilder sb = new StringBuilder();
sb.append("¡Muchas gracias por su compra!\n\n");
sb.append("Recuerde retirarlo en ");
sb.append(cart.getNode().getNode().getAddress().toString()).append(" el ");
sb.append(cart.getNode().getOpen());
txtDescription.setText(sb.toString());
}
cartViewModel.restart();
btnSeguirComprando.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Navigation.findNavController(v).navigate(R.id.nav_products);
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_final, container, false);
}
}
\ No newline at end of file
......@@ -23,12 +23,8 @@ import com.cesanelli.lajusta.io.models.ActiveNode;
import com.cesanelli.lajusta.io.models.Cart;
import com.cesanelli.lajusta.io.models.General;
import com.cesanelli.lajusta.ui.viewmodel.CartViewModel;
import com.cesanelli.lajusta.ui.viewmodel.UserViewModel;
import kotlin.text.Charsets;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Sink;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
......@@ -70,6 +66,8 @@ public class PurchaseFragment extends Fragment implements PurchaseRecyclerViewAd
}
});
cartViewModel = new ViewModelProvider(getActivity()).get(CartViewModel.class);
UserViewModel userViewModel = new ViewModelProvider(getActivity()).get(UserViewModel.class);
cartViewModel.setUser(userViewModel.getToken().getValue().getUser());
cartViewModel.getCart().observe(getActivity(), cart -> {
if (cart != null) {
TextView txtQuantity = view.findViewById(R.id.txtQuantity);
......@@ -77,7 +75,7 @@ public class PurchaseFragment extends Fragment implements PurchaseRecyclerViewAd
TextView txtTotal = view.findViewById(R.id.txtTotal);
txtTotal.setText(String.valueOf(cart.getTotal()));
}
btnComprar.setEnabled(cart.getNode()!=null);
btnComprar.setEnabled(cart.getNode() != null && cart.getTotal() > 0);
});
btnComprar.setOnClickListener(new View.OnClickListener() {
......@@ -88,29 +86,20 @@ public class PurchaseFragment extends Fragment implements PurchaseRecyclerViewAd
@Override
public void onResponse(Call<Cart> call, Response<Cart> response) {
try {
Buffer sink = new Buffer();
BufferedSink bufferedSink = Okio.buffer((Sink) sink);
call.request().body().writeTo(sink);
int ch;
StringBuilder sb = new StringBuilder();
while((ch = sink.inputStream().read()) != -1)
sb.append((char)ch);
String aux = sb.toString();
if (response.isSuccessful()) {
Toast.makeText(getContext(), "Carrito grabado correctamente!", Toast.LENGTH_LONG).show();
Navigation.findNavController(v).navigate(R.id.nav_purchase);
Navigation.findNavController(v).navigate(R.id.nav_final);
} else {
System.out.println(response.toString());
}
System.out.println(response.toString());
} catch (Exception ex) {
System.out.println(ex.toString());
Toast.makeText(getContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Cart> call, Throwable t) {
System.out.println(t.getMessage());
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
......
......@@ -117,7 +117,7 @@ public class RegisterFragment extends Fragment {
private boolean validateEmail() {
String email = user_email.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
String emailPattern = "([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})";
if (!email.matches(emailPattern)) {
user_email.setError("El email es inválido.");
return false;
......
......@@ -8,6 +8,7 @@ import com.cesanelli.lajusta.io.models.ActiveNode;
import com.cesanelli.lajusta.io.models.Cart;
import com.cesanelli.lajusta.io.models.CartItem;
import com.cesanelli.lajusta.io.models.Product;
import com.cesanelli.lajusta.io.models.User;
import java.util.List;
......@@ -95,10 +96,26 @@ public class CartViewModel extends ViewModel {
this.cart.setValue(cart);
}
public void restart(){
Cart newCart = cart.getValue();
for (CartItem cartItem : newCart.getCartProducts()) {
this.deleteProduct(cartItem.getProduct().getId());
}
this.setNode(null);
}
public void setNode (ActiveNode node){
CartItem cartItem = null;
Cart cart = this.cart.getValue();
cart.setNode(node);
this.cart.setValue(cart);
}
public void setUser (User user){
CartItem cartItem = null;
Cart cart = this.cart.getValue();
cart.setUser(user);
this.cart.setValue(cart);
}
}
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24" android:viewportWidth="24"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M21,19V5c0,-1.1 -0.9,-2 -2,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2zM8.5,13.5l2.5,3.01L14.5,12l4.5,6H5l3.5,-4.5z"/>
</vector>
......@@ -46,17 +46,9 @@
android:id="@+id/product_price"
android:layout_width="50dp"
android:layout_height="75dp"
android:layout_toStartOf="@id/product_unit"
android:gravity="end|center_vertical"
android:text="@{`$ ` + String.format(`%.2f`, cartItem.product.buyPrice)}" />
<TextView
android:id="@+id/product_unit"
android:layout_width="50dp"
android:layout_height="75dp"
android:layout_toStartOf="@id/cant_layout"
android:gravity="end|center_vertical"
android:text="@{cartItem.product.unitQuantity + ` ` + cartItem.product.unit.code}" />
android:text="@{`$ ` + String.format(`%.2f`, cartItem.product.buyPrice)}" />
<LinearLayout
android:id="@+id/cant_layout"
......
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="@+id/layoutPurchase"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.PurchaseFragment">
<TextView
android:id="@+id/txtFinalizarCompra"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="@string/compra_finalizada"
app:layout_constraintBottom_toTopOf="@+id/txtDescription"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/txtDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:gravity="center"
app:layout_constraintBottom_toTopOf="@+id/btnSeguirComprando"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/txtFinalizarCompra" />
<Button
android:id="@+id/btnSeguirComprando"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="Seguir Comprando"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtDescription" />
</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file
......@@ -39,16 +39,6 @@
android:text="@{String.format(`%.2f`, productViewModel.product.buyPrice)}"
android:textSize="24sp" />
<TextView
android:id="@+id/product_unit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:gravity="center"
android:text="@{productViewModel.product.unitQuantity + ` ` + productViewModel.product.unit.code}"
android:textSize="24sp" />
<TextView
android:id="@+id/product_description"
android:layout_width="match_parent"
......
......@@ -48,17 +48,17 @@
android:id="@+id/product_price"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_toStartOf="@id/product_unit"
android:layout_toStartOf="@id/product_stock"
android:gravity="end|center_vertical"
android:text="@{`$ ` + String.format(`%.2f`, product.buyPrice)}" />
<TextView
android:id="@+id/product_unit"
android:id="@+id/product_stock"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_toStartOf="@id/product_add"
android:gravity="end|center_vertical"
android:text="@{product.unitQuantity + ` ` + product.unit.code}" />
android:text="@{product.getStock + ` u`}" />
<ImageButton
android:id="@+id/product_add"
......
......@@ -61,7 +61,7 @@
</LinearLayout>
<TextView
android:id="@+id/txtNodo"
android:id="@+id/txtDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
......@@ -80,7 +80,7 @@
app:layout_constraintBottom_toTopOf="@id/btnComprar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/txtNodo"
app:layout_constraintTop_toBottomOf="@id/txtDescription"
tools:listitem="@layout/fragment_node">
</androidx.recyclerview.widget.RecyclerView>
......
......@@ -84,10 +84,21 @@
android:id="@+id/action_nav_purchase_to_nav_products"
app:destination="@id/nav_products"
app:popUpTo="@id/nav_products" />
<action
android:id="@+id/action_nav_purchase_to_purchaseFinalFragment"
app:destination="@id/nav_final" />
</fragment>
<fragment
android:id="@+id/nav_news"
android:name="com.cesanelli.lajusta.ui.NewsFragment"
android:label="@string/menu_news"
tools:layout="@layout/fragment_news" />
<fragment
android:id="@+id/nav_final"
android:name="com.cesanelli.lajusta.ui.PurchaseFinalFragment"
android:label="@string/menu_final">
<action
android:id="@+id/action_purchaseFinalFragment_to_nav_products"
app:destination="@id/nav_products" />
</fragment>
</navigation>
\ No newline at end of file
......@@ -15,6 +15,7 @@
<string name="menu_register">Registrar</string>
<string name="menu_cart">Carrito de Compras</string>
<string name="menu_purchase">Detalle Compra</string>
<string name="menu_final">Gracias por su compra</string>
<string name="txt_username">Usuario</string>
<string name="password">Password</string>
<string name="retry_password">Reiterar Password</string>
......@@ -27,4 +28,5 @@
<string name="finalizar_compra">Detalle final de la compra</string>
<string name="seleccione_punto_de_retiro">Seleccione punto de retiro</string>
<string name="confirmar">Confirmar</string>
<string name="compra_finalizada">Compra Finalizada</string>
</resources>
\ No newline at end of file
Markdown is supported
0%