Tesis 1.0.0
Loading...
Searching...
No Matches
DatosEntregaFragment.java
Go to the documentation of this file.
1package com.example.food_front;
2
3import android.os.Bundle;
4import androidx.fragment.app.Fragment;
5import androidx.fragment.app.FragmentManager;
6import androidx.fragment.app.FragmentTransaction;
7import android.util.Log;
8import android.view.LayoutInflater;
9import android.view.View;
10import android.view.ViewGroup;
11import android.widget.Button;
12import android.widget.EditText;
13import android.widget.TextView;
14import android.widget.Toast;
15import com.android.volley.Request;
16import com.android.volley.RequestQueue;
17import com.android.volley.Response;
18import com.android.volley.VolleyError;
19import com.android.volley.toolbox.StringRequest;
20import com.android.volley.toolbox.Volley;
21import com.example.food_front.utils.ProfileManager;
22import com.example.food_front.utils.SessionManager;
23import com.google.android.material.snackbar.Snackbar;
24
25import java.util.HashMap;
26import java.util.Map;
27
28public class DatosEntregaFragment extends Fragment {
29
30 private double totalCompra = 0;
31 // Umbral para autenticación biométrica: $50,000
32 private static final double UMBRAL_AUTENTICACION = 50000;
33
35 // Required empty constructor
36 }
37
38 // Método estático para crear una nueva instancia con el total de la compra
39 public static DatosEntregaFragment newInstance(double total) {
41 Bundle args = new Bundle();
42 args.putDouble("totalCompra", total);
43 fragment.setArguments(args);
44 return fragment;
45 }
46
47 @Override
48 public void onCreate(Bundle savedInstanceState) {
49 super.onCreate(savedInstanceState);
50 if (getArguments() != null) {
51 totalCompra = getArguments().getDouble("totalCompra", 0);
52 }
53 }
54
55 @Override
56 public View onCreateView(LayoutInflater inflater, ViewGroup container,
57 Bundle savedInstanceState) {
58 // Inflate the layout for this fragment
59 View view = inflater.inflate(R.layout.fragment_datos_entrega, container, false);
60
61 // Obtener la dirección guardada en el login
62 EditText editTextDireccion = view.findViewById(R.id.editTextDireccionEntrega);
63 ProfileManager profileManager = new ProfileManager(requireContext());
64 String direccion = profileManager.getAddress();
65 if (direccion != null && !direccion.isEmpty()) {
66 editTextDireccion.setText(direccion);
67 }
68
69 // Asignar valores aleatorios a tiempo y costo de envío
70 TextView tvTiempo = view.findViewById(R.id.tvSubTitle2);
71 TextView tvCosto = view.findViewById(R.id.tvSubTitle3);
72 int minTiempo = 20 + (int)(Math.random() * 21); // 20-40 min
73 int maxTiempo = minTiempo + 5 + (int)(Math.random() * 11); // +5 a +15 min
74 int costoEnvio = 2000 + (int)(Math.random() * 2001); // $2000-$4000
75 tvTiempo.setText(minTiempo + " - " + maxTiempo + " min");
76 tvCosto.setText("$" + costoEnvio);
77
78 // Find the button and set the click listener
79 Button button = view.findViewById(R.id.btnHacerPedido);
80 button.setOnClickListener(new View.OnClickListener() {
81 @Override
82 public void onClick(View v) {
83 // Call the hacerPedido()
84 hacerPedido();
85 }
86 });
87
88 return view;
89 }
90
94 private void hacerPedido() {
95 EditText editTextDireccion = getView().findViewById(R.id.editTextDireccionEntrega);
96 String nuevaDireccion = editTextDireccion.getText().toString().trim();
97 ProfileManager profileManager = new ProfileManager(requireContext());
98 String direccionGuardada = profileManager.getAddress();
99
100 if (nuevaDireccion.isEmpty()) {
101 Toast.makeText(requireContext(), "Por favor ingresa una dirección de entrega", Toast.LENGTH_SHORT).show();
102 return;
103 }
104
105 if (!nuevaDireccion.equals(direccionGuardada)) {
106 // Consumir endpoint para actualizar dirección de perfil
107 actualizarDireccionPerfil(nuevaDireccion);
108 } else {
109 // Si no cambió, continuar flujo normal
110 replaceFragment(new PaymentFragment());
111 }
112 }
113
114 private void actualizarDireccionPerfil(String nuevaDireccion) {
115 String url = "https://backmobile1.onrender.com/appUSERS/update/";
116 SessionManager sessionManager = new SessionManager(requireContext());
117 String token = sessionManager.getToken();
118 if (token == null) {
119 Toast.makeText(requireContext(), "No hay sesión activa", Toast.LENGTH_SHORT).show();
120 return;
121 }
122 // Mostrar progreso
123 android.app.ProgressDialog progressDialog = new android.app.ProgressDialog(requireContext());
124 progressDialog.setMessage("Actualizando dirección...");
125 progressDialog.setCancelable(false);
126 progressDialog.show();
127 org.json.JSONObject body = new org.json.JSONObject();
128 try {
129 body.put("direccion", nuevaDireccion);
130 } catch (org.json.JSONException e) {
131 progressDialog.dismiss();
132 Toast.makeText(requireContext(), "Error al preparar los datos", Toast.LENGTH_SHORT).show();
133 return;
134 }
135 com.android.volley.toolbox.JsonObjectRequest request = new com.android.volley.toolbox.JsonObjectRequest(
136 com.android.volley.Request.Method.PUT,
137 url,
138 body,
139 response -> {
140 progressDialog.dismiss();
141 // Guardar localmente la nueva dirección usando saveInfo con los datos actuales
142 ProfileManager profileManager = new ProfileManager(requireContext());
143 String nombre = profileManager.getName();
144 String apellido = profileManager.getSurname();
145 String email = profileManager.getEmail();
146 String telefono = profileManager.getPhone();
147 String imagen = profileManager.getProfileImageUrl();
148 profileManager.saveInfo(nombre, apellido, email, telefono, imagen, nuevaDireccion);
149 Toast.makeText(requireContext(), "Dirección actualizada", Toast.LENGTH_SHORT).show();
150 // Continuar con el flujo normal
151 replaceFragment(new PaymentFragment());
152 },
153 error -> {
154 progressDialog.dismiss();
155 String msg = "Error al actualizar dirección";
156 if (error.networkResponse != null) {
157 msg += ". Código: " + error.networkResponse.statusCode;
158 try {
159 String bodyStr = new String(error.networkResponse.data, "UTF-8");
160 msg += "\n" + bodyStr;
161 } catch (Exception ignored) {}
162 }
163 Toast.makeText(requireContext(), msg, Toast.LENGTH_LONG).show();
164 }
165 ) {
166 @Override
167 public Map<String, String> getHeaders() throws com.android.volley.AuthFailureError {
168 Map<String, String> headers = new HashMap<>();
169 headers.put("Authorization", "Bearer " + token);
170 headers.put("Content-Type", "application/json");
171 return headers;
172 }
173 };
174 com.android.volley.RequestQueue queue = com.android.volley.toolbox.Volley.newRequestQueue(requireContext());
175 queue.add(request);
176 }
177
178 private void replaceFragment(Fragment newFragment) {
179 if (isAdded()) {
180 FragmentManager fragmentManager = requireActivity().getSupportFragmentManager();
181 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
182
183 // Si el fragmento de destino es el de pago y el total supera el umbral
184 // redirigimos al fragmento de autenticación por huella
185 if (newFragment instanceof PaymentFragment && totalCompra >= UMBRAL_AUTENTICACION) {
186 FingerprintAuthFragment authFragment = FingerprintAuthFragment.newInstance(totalCompra);
187 fragmentTransaction.replace(R.id.fragment_container_view, authFragment);
188 } else {
189 fragmentTransaction.replace(R.id.fragment_container_view, newFragment);
190 }
191
192 fragmentTransaction.addToBackStack(null);
193 fragmentTransaction.commit();
194 }
195 }
196}
static DatosEntregaFragment newInstance(double total)
View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)