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; ...@@ -20,6 +20,7 @@ import androidx.navigation.ui.NavigationUI;
import com.cesanelli.lajusta.io.ApiAdapter; import com.cesanelli.lajusta.io.ApiAdapter;
import com.cesanelli.lajusta.io.models.Token; import com.cesanelli.lajusta.io.models.Token;
import com.cesanelli.lajusta.io.models.User; import com.cesanelli.lajusta.io.models.User;
import com.cesanelli.lajusta.ui.viewmodel.CartViewModel;
import com.cesanelli.lajusta.ui.viewmodel.UserViewModel; import com.cesanelli.lajusta.ui.viewmodel.UserViewModel;
import com.google.android.material.navigation.NavigationView; import com.google.android.material.navigation.NavigationView;
...@@ -88,6 +89,7 @@ public class MainActivity extends AppCompatActivity { ...@@ -88,6 +89,7 @@ public class MainActivity extends AppCompatActivity {
Token token = new Token(); Token token = new Token();
try { try {
if (response.isSuccessful()) { if (response.isSuccessful()) {
token.setValue(jwt); token.setValue(jwt);
token.setUser(response.body()); token.setUser(response.body());
} else { } else {
......
...@@ -23,7 +23,8 @@ public class ApiAdapter { ...@@ -23,7 +23,8 @@ public class ApiAdapter {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging); 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) { if (API_SERVICE == null) {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
......
...@@ -8,6 +8,7 @@ public class Cart { ...@@ -8,6 +8,7 @@ public class Cart {
private Integer quantity; private Integer quantity;
private float total; private float total;
private ActiveNode nodeDate; private ActiveNode nodeDate;
private User user;
public Cart() { public Cart() {
cartProducts = new ArrayList<CartItem>(); cartProducts = new ArrayList<CartItem>();
...@@ -48,4 +49,28 @@ public class Cart { ...@@ -48,4 +49,28 @@ public class Cart {
public void setNode(ActiveNode node) { public void setNode(ActiveNode node) {
this.nodeDate = 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 { ...@@ -9,6 +9,9 @@ public class CartItem {
this.quantity = quantity; this.quantity = quantity;
} }
public CartItem() {
}
public Product getProduct() { public Product getProduct() {
return product; return product;
} }
......
...@@ -2,11 +2,14 @@ package com.cesanelli.lajusta.io.models; ...@@ -2,11 +2,14 @@ package com.cesanelli.lajusta.io.models;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.util.Base64; import android.util.Base64;
import android.widget.ImageView; import android.widget.ImageView;
import androidx.databinding.BindingAdapter; import androidx.databinding.BindingAdapter;
import com.cesanelli.lajusta.R;
public class Product { public class Product {
private int id; private int id;
private String title; private String title;
...@@ -16,8 +19,7 @@ public class Product { ...@@ -16,8 +19,7 @@ public class Product {
private boolean isPromotion; private boolean isPromotion;
private Category[] categories; private Category[] categories;
private Image[] images; private Image[] images;
private Unit unit; private int stock;
private int unitQuantity;
public int getId() { public int getId() {
return id; return id;
...@@ -83,20 +85,12 @@ public class Product { ...@@ -83,20 +85,12 @@ public class Product {
this.images = images; this.images = images;
} }
public Unit getUnit() { public int getStock() {
return unit; return stock;
}
public void setUnit(Unit unit) {
this.unit = unit;
}
public int getUnitQuantity() {
return unitQuantity;
} }
public void setUnitQuantity(int unitQuantity) { public void setStock(int stock) {
this.unitQuantity = unitQuantity; this.stock = stock;
} }
@BindingAdapter("android:productImage") @BindingAdapter("android:productImage")
...@@ -106,6 +100,9 @@ public class Product { ...@@ -106,6 +100,9 @@ public class Product {
byte[] decodedString = Base64.decode(cleanImage, Base64.DEFAULT); byte[] decodedString = Base64.decode(cleanImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte); imageView.setImageBitmap(decodedByte);
} else {
imageView.setImageResource(R.drawable.ic_baseline_image_24);
imageView.setColorFilter( 0xffcccccc, PorterDuff.Mode.MULTIPLY );
} }
} }
......
package com.cesanelli.lajusta.ui; package com.cesanelli.lajusta.ui;
import android.os.Bundle; import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
...@@ -18,16 +17,9 @@ import androidx.recyclerview.widget.RecyclerView; ...@@ -18,16 +17,9 @@ import androidx.recyclerview.widget.RecyclerView;
import com.cesanelli.lajusta.R; import com.cesanelli.lajusta.R;
import com.cesanelli.lajusta.databinding.FragmentCartListBinding; 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.CartItem;
import com.cesanelli.lajusta.io.models.User;
import com.cesanelli.lajusta.ui.viewmodel.CartViewModel; import com.cesanelli.lajusta.ui.viewmodel.CartViewModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CartFragment extends Fragment implements CartRecyclerViewAdapter.OnCartListener { public class CartFragment extends Fragment implements CartRecyclerViewAdapter.OnCartListener {
private FragmentCartListBinding fragmentCartListBinding; private FragmentCartListBinding fragmentCartListBinding;
private CartViewModel cartViewModel; private CartViewModel cartViewModel;
...@@ -66,6 +58,7 @@ public class CartFragment extends Fragment implements CartRecyclerViewAdapter.On ...@@ -66,6 +58,7 @@ public class CartFragment extends Fragment implements CartRecyclerViewAdapter.On
recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(new CartRecyclerViewAdapter(cart, this)); recyclerView.setAdapter(new CartRecyclerViewAdapter(cart, this));
fragmentCartListBinding.setCart(cart); fragmentCartListBinding.setCart(cart);
btnComprar.setEnabled(cart.getTotal() > 0);
} }
}); });
...@@ -81,12 +74,15 @@ public class CartFragment extends Fragment implements CartRecyclerViewAdapter.On ...@@ -81,12 +74,15 @@ public class CartFragment extends Fragment implements CartRecyclerViewAdapter.On
public void onProductRemove(CartItem cartItem) { public void onProductRemove(CartItem cartItem) {
cartViewModel.deleteProduct(cartItem.getProduct().getId()); cartViewModel.deleteProduct(cartItem.getProduct().getId());
Toast.makeText(getContext(), "Se eliminó " + cartItem.getProduct().getTitle() + " al carrito.", Toast.LENGTH_SHORT).show(); Toast.makeText(getContext(), "Se eliminó " + cartItem.getProduct().getTitle() + " al carrito.", Toast.LENGTH_SHORT).show();
} }
@Override @Override
public void onAddQuantity(CartItem cartItem) { 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 @Override
......
...@@ -78,21 +78,23 @@ public class LoginFragment extends Fragment { ...@@ -78,21 +78,23 @@ public class LoginFragment extends Fragment {
sharedpreferences.edit().putString("UserID", Integer.toString(token.getUser().getId())).apply(); sharedpreferences.edit().putString("UserID", Integer.toString(token.getUser().getId())).apply();
UserViewModel userViewModel = new ViewModelProvider(getActivity()).get(UserViewModel.class); UserViewModel userViewModel = new ViewModelProvider(getActivity()).get(UserViewModel.class);
userViewModel.setToken(token); 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); Navigation.findNavController(v).navigate(R.id.nav_products);
} else {
Toast.makeText(getContext(), "Usuario o password incorrectos.", Toast.LENGTH_LONG).show();
} }
} catch (Exception ex) { } 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 @Override
public void onFailure(Call<Token> call, Throwable t) { 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 ...@@ -91,8 +91,12 @@ public class ProductsFragment extends Fragment implements ProductsRecyclerViewAd
@Override @Override
public void onProductAdd(Product product) { public void onProductAdd(Product product) {
cartViewModel.addProduct(product); if(product.getStock()>0){
Toast.makeText(getContext(), "Se agregó " + product.getTitle() + " al carrito.", Toast.LENGTH_SHORT).show(); 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 @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; ...@@ -23,12 +23,8 @@ import com.cesanelli.lajusta.io.models.ActiveNode;
import com.cesanelli.lajusta.io.models.Cart; import com.cesanelli.lajusta.io.models.Cart;
import com.cesanelli.lajusta.io.models.General; import com.cesanelli.lajusta.io.models.General;
import com.cesanelli.lajusta.ui.viewmodel.CartViewModel; 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.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -70,6 +66,8 @@ public class PurchaseFragment extends Fragment implements PurchaseRecyclerViewAd ...@@ -70,6 +66,8 @@ public class PurchaseFragment extends Fragment implements PurchaseRecyclerViewAd
} }
}); });
cartViewModel = new ViewModelProvider(getActivity()).get(CartViewModel.class); 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 -> { cartViewModel.getCart().observe(getActivity(), cart -> {
if (cart != null) { if (cart != null) {
TextView txtQuantity = view.findViewById(R.id.txtQuantity); TextView txtQuantity = view.findViewById(R.id.txtQuantity);
...@@ -77,7 +75,7 @@ public class PurchaseFragment extends Fragment implements PurchaseRecyclerViewAd ...@@ -77,7 +75,7 @@ public class PurchaseFragment extends Fragment implements PurchaseRecyclerViewAd
TextView txtTotal = view.findViewById(R.id.txtTotal); TextView txtTotal = view.findViewById(R.id.txtTotal);
txtTotal.setText(String.valueOf(cart.getTotal())); txtTotal.setText(String.valueOf(cart.getTotal()));
} }
btnComprar.setEnabled(cart.getNode()!=null); btnComprar.setEnabled(cart.getNode() != null && cart.getTotal() > 0);
}); });
btnComprar.setOnClickListener(new View.OnClickListener() { btnComprar.setOnClickListener(new View.OnClickListener() {
...@@ -88,29 +86,20 @@ public class PurchaseFragment extends Fragment implements PurchaseRecyclerViewAd ...@@ -88,29 +86,20 @@ public class PurchaseFragment extends Fragment implements PurchaseRecyclerViewAd
@Override @Override
public void onResponse(Call<Cart> call, Response<Cart> response) { public void onResponse(Call<Cart> call, Response<Cart> response) {
try { 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()) { if (response.isSuccessful()) {
Toast.makeText(getContext(), "Carrito grabado correctamente!", Toast.LENGTH_LONG).show(); 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) { } catch (Exception ex) {
System.out.println(ex.toString()); System.out.println(ex.toString());
Toast.makeText(getContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
} }
} }
@Override @Override
public void onFailure(Call<Cart> call, Throwable t) { public void onFailure(Call<Cart> call, Throwable t) {
System.out.println(t.getMessage()); System.out.println(t.getMessage());
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
} }
}); });
......
...@@ -117,7 +117,7 @@ public class RegisterFragment extends Fragment { ...@@ -117,7 +117,7 @@ public class RegisterFragment extends Fragment {
private boolean validateEmail() { private boolean validateEmail() {
String email = user_email.getText().toString().trim(); 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)) { if (!email.matches(emailPattern)) {
user_email.setError("El email es inválido."); user_email.setError("El email es inválido.");
return false; return false;
......
...@@ -8,6 +8,7 @@ import com.cesanelli.lajusta.io.models.ActiveNode; ...@@ -8,6 +8,7 @@ import com.cesanelli.lajusta.io.models.ActiveNode;
import com.cesanelli.lajusta.io.models.Cart; import com.cesanelli.lajusta.io.models.Cart;
import com.cesanelli.lajusta.io.models.CartItem; import com.cesanelli.lajusta.io.models.CartItem;
import com.cesanelli.lajusta.io.models.Product; import com.cesanelli.lajusta.io.models.Product;
import com.cesanelli.lajusta.io.models.User;
import java.util.List; import java.util.List;
...@@ -95,10 +96,26 @@ public class CartViewModel extends ViewModel { ...@@ -95,10 +96,26 @@ public class CartViewModel extends ViewModel {
this.cart.setValue(cart); 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){ public void setNode (ActiveNode node){
CartItem cartItem = null; CartItem cartItem = null;
Cart cart = this.cart.getValue(); Cart cart = this.cart.getValue();
cart.setNode(node); cart.setNode(node);
this.cart.setValue(cart); 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 @@ ...@@ -46,17 +46,9 @@
android:id="@+id/product_price" android:id="@+id/product_price"
android:layout_width="50dp" android:layout_width="50dp"
android:layout_height="75dp" 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"