Compare commits

..

12 Commits

Author SHA1 Message Date
d5c457c9a6 ... 2026-02-24 16:38:44 +00:00
526da66c5f ... 2026-02-19 10:32:45 +00:00
a715199bbe Merge remote-tracking branch 'origin/main' 2026-02-03 15:55:53 +00:00
2f2719101f ... 2026-02-03 15:55:42 +00:00
f9b1b4fc5d ... 2026-02-03 10:38:33 +00:00
e582e7ce6b ... 2026-02-03 09:59:28 +00:00
2e7e22c89a Add test credentials to layout 2026-02-03 09:13:58 +00:00
ccd2323114 credenciais 2026-02-03 09:11:36 +00:00
cf578e17b8 Add Readme.md 2026-02-03 09:09:05 +00:00
2e3b914d50 ecra principal 2026-02-03 09:03:17 +00:00
1c68112436 ecra principal 2026-01-29 10:40:21 +00:00
906849e4b7 ecra principal 2026-01-28 18:04:32 +00:00
20 changed files with 711 additions and 240 deletions

13
.idea/deviceManager.xml generated Normal file
View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DeviceTable">
<option name="columnSorters">
<list>
<ColumnSorterState>
<option name="column" value="Name" />
<option name="order" value="ASCENDING" />
</ColumnSorterState>
</list>
</option>
</component>
</project>

8
.idea/markdown.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MarkdownSettings">
<option name="previewPanelProviderInfo">
<ProviderInfo name="Compose (experimental)" className="com.intellij.markdown.compose.preview.ComposePanelProvider" />
</option>
</component>
</project>

1
.idea/misc.xml generated
View File

@@ -1,4 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">

3
Readme.md Normal file
View File

@@ -0,0 +1,3 @@
EstabelecimentoPap@gmail.com
PaP@P.1

View File

@@ -41,6 +41,7 @@ dependencies {
implementation(platform(libs.firebase.bom))
implementation("com.google.firebase:firebase-firestore")
implementation("com.google.firebase:firebase-auth")
implementation(libs.firebase.database)
testImplementation(libs.junit)
androidTestImplementation(libs.ext.junit)
androidTestImplementation(libs.espresso.core)

View File

@@ -2,6 +2,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
@@ -11,6 +13,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Pap_teste">
<activity
android:name=".AddStaffActivity"
android:exported="false" />
<activity
android:name=".DetalhesReservasActivity"
android:exported="false"

View File

@@ -0,0 +1,130 @@
package com.example.pap_teste;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.text.InputType;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.example.pap_teste.models.Staff;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class AddStaffActivity extends AppCompatActivity {
private Button addButton;
private EditText nameEditText;
private Spinner zonaSpinner;
private Button btnAddZone;
private Spinner mesaSpinner;
private ArrayList<String> zones;
private ArrayList<String> mesas;
private ArrayAdapter<String> adapter;
private ArrayAdapter<String> mesaAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_add_staff);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
addButton = findViewById(R.id.addButton);
nameEditText = findViewById(R.id.nammeEditText);
zonaSpinner = findViewById(R.id.zonaSpinner);
btnAddZone = findViewById(R.id.btnAddZone);
mesaSpinner = findViewById(R.id.mesaSpinner);
zones = new ArrayList<>();
zones.add("Sala");
zones.add("Esplanada");
zones.add("Balcão");
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, zones);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
zonaSpinner.setAdapter(adapter);
mesas = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
mesas.add("Mesa " + i);
}
mesaAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mesas);
mesaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mesaSpinner.setAdapter(mesaAdapter);
btnAddZone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(AddStaffActivity.this);
builder.setTitle("Adicionar Zona");
final EditText input = new EditText(AddStaffActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newZone = input.getText().toString();
if (!newZone.isEmpty()) {
zones.add(newZone);
adapter.notifyDataSetChanged();
zonaSpinner.setSelection(zones.size() - 1);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = nameEditText.getText().toString();
String zona = "";
if (zonaSpinner.getSelectedItem() != null) {
zona = zonaSpinner.getSelectedItem().toString();
}
String mesa = "";
if (mesaSpinner.getSelectedItem() != null) {
mesa = mesaSpinner.getSelectedItem().toString();
}
if (!name.isEmpty()) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Staff");
String uuid = java.util.UUID.randomUUID().toString();
Staff staff = new Staff(name, zona, mesa, uuid);
databaseReference.child(uuid).setValue(staff);
Toast.makeText(AddStaffActivity.this, "Staff adicionado com sucesso!", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(AddStaffActivity.this, "Erro: Preencha todos os campos", Toast.LENGTH_SHORT).show();
}
}
});
}
}

View File

@@ -76,10 +76,5 @@ public class ClientDashboardActivity extends AppCompatActivity {
btnBack.setOnClickListener(v -> finish());
}
}
// Mantemos este método caso seja útil no futuro para feedback rápido.
// private void showToast(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
}

View File

@@ -75,10 +75,5 @@ public class EstablishmentDashboardActivity extends AppCompatActivity {
btnBack.setOnClickListener(v -> finish());
}
}
// Mantemos este método caso seja útil no futuro para feedback rápido.
// private void showToast(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
}

View File

@@ -15,18 +15,28 @@ import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.example.pap_teste.models.Mesa;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
public class GerirMesasActivity extends AppCompatActivity {
private final List<MesaItem> mesas = new ArrayList<>();
private final List<Mesa> mesas = new ArrayList<>();
private ArrayAdapter<String> adapter;
private ListView listMesas;
private EditText inputNumero;
private EditText inputCapacidade;
private Spinner spinnerEstado;
private TextView txtMensagem;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -40,7 +50,9 @@ public class GerirMesasActivity extends AppCompatActivity {
});
bindViews();
seedMesasDemo();
mDatabase = FirebaseDatabase.getInstance().getReference("Mesas");
setupList();
setupFormActions();
}
@@ -60,29 +72,44 @@ public class GerirMesasActivity extends AppCompatActivity {
ArrayAdapter<String> estadoAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_spinner_dropdown_item,
new String[]{"Livre", "Ocupada", "Reservada"}
);
new String[] { "Livre", "Ocupada", "Reservada" });
spinnerEstado.setAdapter(estadoAdapter);
}
private void seedMesasDemo() {
mesas.add(new MesaItem(1, 4, "Livre"));
mesas.add(new MesaItem(2, 2, "Reservada"));
mesas.add(new MesaItem(3, 6, "Ocupada"));
mesas.add(new MesaItem(4, 4, "Livre"));
}
private void setupList() {
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1);
listMesas.setAdapter(adapter);
refreshList();
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
mesas.clear();
adapter.clear();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Mesa mesa = postSnapshot.getValue(Mesa.class);
if (mesa != null) {
mesas.add(mesa);
String resumo = String.format("Mesa %02d • %d lugares • %s", mesa.getNumero(),
mesa.getCapacidade(), mesa.getEstado());
adapter.add(resumo);
}
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(GerirMesasActivity.this, "Erro ao carregar mesas: " + error.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
listMesas.setOnItemClickListener((parent, view, position, id) -> {
MesaItem item = mesas.get(position);
inputNumero.setText(String.valueOf(item.numero));
inputCapacidade.setText(String.valueOf(item.capacidade));
spinnerEstado.setSelection(getEstadoIndex(item.estado));
txtMensagem.setText(String.format("Editar mesa %d", item.numero));
Mesa item = mesas.get(position);
inputNumero.setText(String.valueOf(item.getNumero()));
inputCapacidade.setText(String.valueOf(item.getCapacidade()));
spinnerEstado.setSelection(getEstadoIndex(item.getEstado()));
txtMensagem.setText(String.format("Editar mesa %d", item.getNumero()));
});
}
@@ -123,56 +150,36 @@ public class GerirMesasActivity extends AppCompatActivity {
return;
}
MesaItem existente = findMesa(numero);
Mesa existente = findMesa(numero);
String mesaId;
if (existente == null) {
mesas.add(new MesaItem(numero, capacidade, estado));
txtMensagem.setText(String.format("Mesa %d adicionada/atualizada.", numero));
mesaId = mDatabase.push().getKey();
Mesa novaMesa = new Mesa(mesaId, numero, capacidade, estado);
if (mesaId != null) {
mDatabase.child(mesaId).setValue(novaMesa);
}
txtMensagem.setText(String.format("Mesa %d adicionada.", numero));
} else {
existente.capacidade = capacidade;
existente.estado = estado;
mesaId = existente.getId();
existente.setCapacidade(capacidade);
existente.setEstado(estado);
mDatabase.child(mesaId).setValue(existente);
txtMensagem.setText(String.format("Mesa %d atualizada.", numero));
}
refreshList();
// Clearing inputs
inputNumero.setText("");
inputCapacidade.setText("");
}
private MesaItem findMesa(int numero) {
for (MesaItem item : mesas) {
if (item.numero == numero) {
private Mesa findMesa(int numero) {
for (Mesa item : mesas) {
if (item.getNumero() == numero) {
return item;
}
}
return null;
}
private void refreshList() {
adapter.clear();
for (MesaItem item : mesas) {
String resumo = String.format("Mesa %02d • %d lugares • %s", item.numero, item.capacidade, item.estado);
adapter.add(resumo);
}
adapter.notifyDataSetChanged();
}
private static class MesaItem {
int numero;
int capacidade;
String estado;
MesaItem(int numero, int capacidade, String estado) {
this.numero = numero;
this.capacidade = capacidade;
this.estado = estado;
}
}
}

View File

@@ -1,9 +1,21 @@
package com.example.pap_teste;
import com.example.pap_teste.models.Mesa;
import com.example.pap_teste.models.Staff;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import androidx.annotation.NonNull;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
@@ -20,13 +32,24 @@ import java.util.List;
public class GestaoStaffActivity extends AppCompatActivity {
private final List<StaffAssignment> staffAssignments = new ArrayList<>();
private final List<Staff> staffList = new ArrayList<>();
private ArrayAdapter<String> staffAdapter;
private ListView listStaffMesas;
private EditText inputNomeStaff;
private Spinner spinnerNomeStaff;
private Spinner spinnerMesaStaff;
private TextView txtMensagemStaff;
private DatabaseReference staffRef;
private DatabaseReference mesasRef;
private List<String> staffNames = new ArrayList<>();
private List<Mesa> mesasDisponiveis = new ArrayList<>();
private ArrayAdapter<String> staffNameAdapter;
private ArrayAdapter<String> mesaSpinnerAdapter;
private FloatingActionButton floatingActionButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -38,6 +61,9 @@ public class GestaoStaffActivity extends AppCompatActivity {
return insets;
});
staffRef = FirebaseDatabase.getInstance().getReference("Staff");
mesasRef = FirebaseDatabase.getInstance().getReference("Mesas");
Button back = findViewById(R.id.btnVoltar);
if (back != null) {
back.setOnClickListener(v -> finish());
@@ -51,9 +77,10 @@ public class GestaoStaffActivity extends AppCompatActivity {
private void bindViews() {
listStaffMesas = findViewById(R.id.listStaffMesas);
inputNomeStaff = findViewById(R.id.inputNomeStaff);
spinnerNomeStaff = findViewById(R.id.spinnerNomeStaff);
spinnerMesaStaff = findViewById(R.id.spinnerMesaStaff);
txtMensagemStaff = findViewById(R.id.txtMensagemStaff);
floatingActionButton = findViewById(R.id.floatingActionButton);
}
/**
@@ -61,29 +88,69 @@ public class GestaoStaffActivity extends AppCompatActivity {
* Mais tarde isto pode ser ligado às mesas reais configuradas em "Gerir Mesas".
*/
private void setupMesaSpinner() {
ArrayAdapter<String> mesaAdapter = new ArrayAdapter<>(
mesaSpinnerAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_spinner_dropdown_item
);
android.R.layout.simple_spinner_dropdown_item);
for (int i = 1; i <= 20; i++) {
mesaAdapter.add(String.format("Mesa %02d", i));
}
staffNameAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_spinner_dropdown_item,
staffNames);
spinnerNomeStaff.setAdapter(staffNameAdapter);
spinnerMesaStaff.setAdapter(mesaAdapter);
loadStaffMembers();
loadMesas();
spinnerMesaStaff.setAdapter(mesaSpinnerAdapter);
}
private void loadMesas() {
mesasRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
mesasDisponiveis.clear();
mesaSpinnerAdapter.clear();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Mesa mesa = postSnapshot.getValue(Mesa.class);
if (mesa != null) {
mesasDisponiveis.add(mesa);
mesaSpinnerAdapter.add("Mesa " + mesa.getNumero());
}
}
mesaSpinnerAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(GestaoStaffActivity.this, "Erro ao carregar mesas.", Toast.LENGTH_SHORT).show();
}
});
}
private void setupList() {
staffAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1);
listStaffMesas.setAdapter(staffAdapter);
refreshList();
listStaffMesas.setOnItemClickListener((parent, view, position, id) -> {
StaffAssignment item = staffAssignments.get(position);
inputNomeStaff.setText(item.nome);
int index = Math.max(0, Math.min(spinnerMesaStaff.getCount() - 1, item.mesaNumero - 1));
spinnerMesaStaff.setSelection(index);
txtMensagemStaff.setText(String.format("A editar: %s (Mesa %02d)", item.nome, item.mesaNumero));
Staff item = staffList.get(position);
// Select staff in spinner
int staffIndex = staffNames.indexOf(item.getName());
if (staffIndex >= 0) {
spinnerNomeStaff.setSelection(staffIndex);
}
// Select mesa in spinner
// Simple string matching for now since Mesa is stored as String in Staff
String assignedMesa = item.getMesa();
if (assignedMesa != null) {
for (int i = 0; i < mesaSpinnerAdapter.getCount(); i++) {
if (mesaSpinnerAdapter.getItem(i).equals(assignedMesa)) {
spinnerMesaStaff.setSelection(i);
break;
}
}
}
txtMensagemStaff.setText(String.format("A editar: %s", item.getName()));
});
}
@@ -92,12 +159,26 @@ public class GestaoStaffActivity extends AppCompatActivity {
if (btnAtribuir != null) {
btnAtribuir.setOnClickListener(v -> guardarAtribuicao());
}
if (floatingActionButton != null) {
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GestaoStaffActivity.this, AddStaffActivity.class);
startActivity(intent);
}
});
}
}
private void guardarAtribuicao() {
String nome = inputNomeStaff != null ? inputNomeStaff.getText().toString().trim() : "";
String nome = "";
if (spinnerNomeStaff.getSelectedItem() != null) {
nome = spinnerNomeStaff.getSelectedItem().toString();
}
if (nome.isEmpty()) {
Toast.makeText(this, "Indique o nome do funcionário.", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Selecione um funcionário.", Toast.LENGTH_SHORT).show();
return;
}
@@ -106,52 +187,64 @@ public class GestaoStaffActivity extends AppCompatActivity {
return;
}
int mesaNumero = spinnerMesaStaff.getSelectedItemPosition() + 1;
String mesaSelecionada = spinnerMesaStaff.getSelectedItem().toString();
StaffAssignment existente = findByNome(nome);
if (existente == null) {
staffAssignments.add(new StaffAssignment(nome, mesaNumero));
txtMensagemStaff.setText(String.format("%s atribuído à mesa %02d.", nome, mesaNumero));
Staff staffToUpdate = findByNome(nome);
if (staffToUpdate != null) {
staffToUpdate.setMesa(mesaSelecionada);
final String finalNome = nome;
final String finalMesa = mesaSelecionada;
staffRef.child(staffToUpdate.getId()).setValue(staffToUpdate)
.addOnSuccessListener(aVoid -> {
txtMensagemStaff.setText(String.format("%s atribuído à %s.", finalNome, finalMesa));
})
.addOnFailureListener(e -> {
Toast.makeText(this, "Erro ao atualizar: " + e.getMessage(), Toast.LENGTH_SHORT).show();
});
} else {
existente.mesaNumero = mesaNumero;
txtMensagemStaff.setText(String.format("Mesa de %s atualizada para %02d.", nome, mesaNumero));
Toast.makeText(this, "Erro: Staff não encontrado.", Toast.LENGTH_SHORT).show();
}
refreshList();
}
private StaffAssignment findByNome(String nome) {
for (StaffAssignment item : staffAssignments) {
if (item.nome.equalsIgnoreCase(nome)) {
private Staff findByNome(String nome) {
for (Staff item : staffList) {
if (item.getName().equalsIgnoreCase(nome)) {
return item;
}
}
return null;
}
private void refreshList() {
if (staffAdapter == null) return;
private void loadStaffMembers() {
staffRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
staffList.clear();
staffNames.clear();
staffAdapter.clear();
staffAdapter.clear();
for (StaffAssignment item : staffAssignments) {
String resumo = String.format("%s • Mesa %02d", item.nome, item.mesaNumero);
staffAdapter.add(resumo);
}
staffAdapter.notifyDataSetChanged();
}
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Staff staff = postSnapshot.getValue(Staff.class);
if (staff != null && staff.getName() != null) {
staffList.add(staff);
staffNames.add(staff.getName());
private static class StaffAssignment {
String nome;
int mesaNumero;
String mesaInfo = staff.getMesa() != null ? staff.getMesa() : "Sem Mesa";
String resumo = String.format("%s • %s • %s", staff.getName(), staff.getZona(), mesaInfo);
staffAdapter.add(resumo);
}
}
StaffAssignment(String nome, int mesaNumero) {
this.nome = nome;
this.mesaNumero = mesaNumero;
}
staffNameAdapter.notifyDataSetChanged();
staffAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(GestaoStaffActivity.this, "Erro ao carregar staff.", Toast.LENGTH_SHORT).show();
}
});
}
}

View File

@@ -18,8 +18,9 @@ import androidx.core.view.WindowInsetsCompat;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.SetOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Map;
@@ -34,8 +35,13 @@ public class MainActivity extends AppCompatActivity {
private static final String PREFS_NAME = "pap_prefs";
private static final String KEY_HAS_CREATED_ACCOUNT = "has_created_account";
public enum AccountType {CLIENTE, ESTABELECIMENTO}
public enum AccountAction {ENTRAR, CRIAR}
public enum AccountType {
CLIENTE, ESTABELECIMENTO
}
public enum AccountAction {
ENTRAR, CRIAR
}
private AccountType selectedAccountType = AccountType.CLIENTE;
private AccountAction selectedAccountAction = AccountAction.ENTRAR;
@@ -54,7 +60,7 @@ public class MainActivity extends AppCompatActivity {
private EditText inputEstablishmentPhone;
private boolean hasCreatedAccount;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore firestore;
private DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -69,13 +75,12 @@ public class MainActivity extends AppCompatActivity {
FirebaseApp.initializeApp(this);
firebaseAuth = FirebaseAuth.getInstance();
firestore = FirebaseFirestore.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
bindViews();
setupTypeToggle();
setupActionToggle();
setupPrimaryAction();
enforceFirstAccountCreation();
}
private void bindViews() {
@@ -170,13 +175,6 @@ public class MainActivity extends AppCompatActivity {
String establishmentEmail = inputEstablishmentEmail.getText().toString().trim();
String establishmentPhone = inputEstablishmentPhone.getText().toString().trim();
if (selectedAccountAction == AccountAction.ENTRAR && !hasCreatedAccount) {
Toast.makeText(this, "Crie uma conta para começar a usar a app.", Toast.LENGTH_SHORT).show();
selectedAccountAction = AccountAction.CRIAR;
updateActionButtons();
return;
}
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
Toast.makeText(this, "Preencha email e palavra-passe.", Toast.LENGTH_SHORT).show();
return;
@@ -184,6 +182,10 @@ public class MainActivity extends AppCompatActivity {
boolean creatingAccount = selectedAccountAction == AccountAction.CRIAR;
if (creatingAccount && !isValidPassword(password)) {
return;
}
if (creatingAccount) {
if (selectedAccountType == AccountType.CLIENTE && TextUtils.isEmpty(providedName)) {
Toast.makeText(this, "Indique o seu nome para criar conta.", Toast.LENGTH_SHORT).show();
@@ -197,7 +199,8 @@ public class MainActivity extends AppCompatActivity {
|| TextUtils.isEmpty(establishmentPhone);
if (missingOwner || missingEstablishment) {
Toast.makeText(this, "Preencha os dados do proprietário e do estabelecimento.", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Preencha os dados do proprietário e do estabelecimento.", Toast.LENGTH_SHORT)
.show();
return;
}
}
@@ -216,8 +219,7 @@ public class MainActivity extends AppCompatActivity {
establishmentEmail,
establishmentPhone,
fallbackName,
resolvedRole
);
resolvedRole);
return;
}
@@ -237,18 +239,6 @@ public class MainActivity extends AppCompatActivity {
return firstLetter + rest;
}
private void enforceFirstAccountCreation() {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
hasCreatedAccount = prefs.getBoolean(KEY_HAS_CREATED_ACCOUNT, false);
if (!hasCreatedAccount) {
selectedAccountAction = AccountAction.CRIAR;
Toast.makeText(this, "Crie uma conta para começar a usar a app.", Toast.LENGTH_SHORT).show();
}
updateActionButtons();
}
private void markAccountCreated() {
hasCreatedAccount = true;
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
@@ -264,7 +254,7 @@ public class MainActivity extends AppCompatActivity {
}
private boolean ensureFirebaseReady() {
boolean ready = firebaseAuth != null && firestore != null;
boolean ready = firebaseAuth != null && databaseReference != null;
if (!ready) {
Toast.makeText(this, "Ligue-se ao Firebase para continuar.", Toast.LENGTH_SHORT).show();
}
@@ -277,12 +267,12 @@ public class MainActivity extends AppCompatActivity {
}
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnSuccessListener(authResult ->
fetchAccountAndNavigate(email, fallbackName, resolvedRole)
)
.addOnFailureListener(e ->
Toast.makeText(this, "Não foi possível iniciar sessão: " + e.getMessage(), Toast.LENGTH_SHORT).show()
);
.addOnSuccessListener(authResult -> fetchAccountAndNavigate(email, fallbackName, resolvedRole))
.addOnFailureListener(e -> {
android.util.Log.e("LoginError", "SignIn failed", e);
Toast.makeText(this, "Não foi possível iniciar sessão: " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
});
}
private void createAccountInFirebase(
@@ -294,8 +284,7 @@ public class MainActivity extends AppCompatActivity {
String establishmentEmail,
String establishmentPhone,
String fallbackName,
String resolvedRole
) {
String resolvedRole) {
if (!ensureFirebaseReady()) {
return;
}
@@ -305,9 +294,10 @@ public class MainActivity extends AppCompatActivity {
if (!hasCreatedAccount) {
markAccountCreated();
}
String finalDisplayName = selectedAccountType == AccountType.ESTABELECIMENTO && !TextUtils.isEmpty(establishmentName)
? establishmentName
: fallbackName;
String finalDisplayName = selectedAccountType == AccountType.ESTABELECIMENTO
&& !TextUtils.isEmpty(establishmentName)
? establishmentName
: fallbackName;
String uid = result.getUser() != null ? result.getUser().getUid() : null;
persistAccountInFirebase(
@@ -320,71 +310,77 @@ public class MainActivity extends AppCompatActivity {
establishmentPhone,
uid,
() -> {
Intent createdScreen = new Intent(this, AccountCreatedActivity.class);
createdScreen.putExtra(EXTRA_ACTION_MODE, selectedAccountAction.name());
createdScreen.putExtra(EXTRA_DISPLAY_NAME, finalDisplayName);
createdScreen.putExtra(EXTRA_EMAIL, email);
createdScreen.putExtra(EXTRA_ACCOUNT_TYPE, selectedAccountType.name());
createdScreen.putExtra(EXTRA_ROLE, resolvedRole);
startActivity(createdScreen);
}
);
Toast.makeText(this, "Conta criada com sucesso! Carregue em Entrar.", Toast.LENGTH_LONG)
.show();
selectedAccountAction = AccountAction.ENTRAR;
updateActionButtons();
});
})
.addOnFailureListener(e ->
Toast.makeText(this, "Falha ao criar conta: " + e.getMessage(), Toast.LENGTH_SHORT).show()
);
.addOnFailureListener(e -> {
android.util.Log.e("LoginError", "CreateUser failed", e);
Toast.makeText(this, "Falha ao criar conta: " + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
private void fetchAccountAndNavigate(String email, String fallbackName, String resolvedRole) {
if (firestore == null) {
if (databaseReference == null) {
Toast.makeText(this, "Firebase indisponível.", Toast.LENGTH_SHORT).show();
navigateToDashboard(email, fallbackName, resolvedRole);
return;
}
String documentId = buildDocumentId(email);
firestore.collection("users")
.document(documentId)
.get()
.addOnSuccessListener(snapshot -> {
if (snapshot == null || !snapshot.exists()) {
Toast.makeText(this, "Conta não encontrada no Firebase.", Toast.LENGTH_SHORT).show();
return;
}
databaseReference.child("users").child(documentId).get().addOnCompleteListener(task -> {
if (!task.isSuccessful()) {
android.util.Log.e("LoginError", "Database check failed", task.getException());
Toast.makeText(this, "Falha ao validar perfil na cloud. A entrar em modo básico.", Toast.LENGTH_SHORT)
.show();
navigateToDashboard(email, fallbackName, resolvedRole);
return;
}
String accountTypeInFirebase = snapshot.getString("accountType");
if (accountTypeInFirebase != null
&& !accountTypeInFirebase.equalsIgnoreCase(selectedAccountType.name())) {
Toast.makeText(this, "Tipo de conta não corresponde ao registo no Firebase.", Toast.LENGTH_SHORT).show();
return;
}
DataSnapshot snapshot = task.getResult();
if (snapshot == null || !snapshot.exists()) {
Toast.makeText(this, "Conta sem perfil na cloud. A entrar em modo básico.", Toast.LENGTH_SHORT).show();
navigateToDashboard(email, fallbackName, resolvedRole);
return;
}
String displayNameFromDb = snapshot.getString("displayName");
String establishmentName = snapshot.getString("establishmentName");
String ownerName = snapshot.getString("ownerName");
String roleFromDb = snapshot.getString("role");
String accountTypeInFirebase = snapshot.child("accountType").getValue(String.class);
if (accountTypeInFirebase != null
&& !accountTypeInFirebase.equalsIgnoreCase(selectedAccountType.name())) {
Toast.makeText(this, "Tipo de conta não corresponde ao registo no Firebase.", Toast.LENGTH_SHORT)
.show();
return;
}
String finalDisplayName = !TextUtils.isEmpty(establishmentName)
? establishmentName
: !TextUtils.isEmpty(displayNameFromDb) ? displayNameFromDb
String displayNameFromDb = snapshot.child("displayName").getValue(String.class);
String establishmentName = snapshot.child("establishmentName").getValue(String.class);
String ownerName = snapshot.child("ownerName").getValue(String.class);
String roleFromDb = snapshot.child("role").getValue(String.class);
String finalDisplayName = !TextUtils.isEmpty(establishmentName)
? establishmentName
: !TextUtils.isEmpty(displayNameFromDb) ? displayNameFromDb
: !TextUtils.isEmpty(ownerName) ? ownerName
: fallbackName;
: fallbackName;
String finalRole = !TextUtils.isEmpty(roleFromDb) ? roleFromDb : resolvedRole;
String finalRole = !TextUtils.isEmpty(roleFromDb) ? roleFromDb : resolvedRole;
navigateToDashboard(email, finalDisplayName, finalRole);
});
}
Intent nextScreen = selectedAccountType == AccountType.CLIENTE
? new Intent(this, ClientDashboardActivity.class)
: new Intent(this, EstablishmentDashboardActivity.class);
private void navigateToDashboard(String email, String displayName, String role) {
Intent nextScreen = selectedAccountType == AccountType.CLIENTE
? new Intent(this, ClientDashboardActivity.class)
: new Intent(this, EstablishmentDashboardActivity.class);
nextScreen.putExtra(EXTRA_ACTION_MODE, selectedAccountAction.name());
nextScreen.putExtra(EXTRA_DISPLAY_NAME, finalDisplayName);
nextScreen.putExtra(EXTRA_EMAIL, email);
nextScreen.putExtra(EXTRA_ACCOUNT_TYPE, selectedAccountType.name());
nextScreen.putExtra(EXTRA_ROLE, finalRole);
startActivity(nextScreen);
})
.addOnFailureListener(e ->
Toast.makeText(this, "Erro ao verificar conta no Firebase.", Toast.LENGTH_SHORT).show()
);
nextScreen.putExtra(EXTRA_ACTION_MODE, selectedAccountAction.name());
nextScreen.putExtra(EXTRA_DISPLAY_NAME, displayName);
nextScreen.putExtra(EXTRA_EMAIL, email);
nextScreen.putExtra(EXTRA_ACCOUNT_TYPE, selectedAccountType.name());
nextScreen.putExtra(EXTRA_ROLE, role);
startActivity(nextScreen);
}
private void persistAccountInFirebase(
@@ -396,9 +392,8 @@ public class MainActivity extends AppCompatActivity {
String establishmentEmail,
String establishmentPhone,
String uid,
Runnable onSuccess
) {
if (firestore == null) {
Runnable onSuccess) {
if (databaseReference == null) {
Toast.makeText(this, "Firebase indisponível.", Toast.LENGTH_SHORT).show();
return;
}
@@ -423,19 +418,40 @@ public class MainActivity extends AppCompatActivity {
payload.put("establishmentPhone", establishmentPhone);
}
firestore.collection("users")
.document(documentId)
.set(payload, SetOptions.merge())
.addOnSuccessListener(unused ->
{
Toast.makeText(this, "Conta guardada na cloud.", Toast.LENGTH_SHORT).show();
if (onSuccess != null) {
onSuccess.run();
}
}
)
.addOnFailureListener(e ->
Toast.makeText(this, "Não foi possível guardar na cloud.", Toast.LENGTH_SHORT).show()
);
databaseReference.child("users").child(documentId).updateChildren(payload)
.addOnSuccessListener(unused -> {
Toast.makeText(this, "Conta guardada na cloud.", Toast.LENGTH_SHORT).show();
if (onSuccess != null) {
onSuccess.run();
}
})
.addOnFailureListener(
e -> Toast.makeText(this, "Não foi possível guardar na cloud.", Toast.LENGTH_SHORT).show());
}
private boolean isValidPassword(String password) {
if (password.length() < 6) {
Toast.makeText(this, "A palavra-passe deve ter pelo menos 6 caracteres.", Toast.LENGTH_SHORT).show();
return false;
}
boolean hasLower = false;
boolean hasDigit = false;
boolean hasSpecial = false;
for (char c : password.toCharArray()) {
if (Character.isLowerCase(c))
hasLower = true;
else if (Character.isDigit(c))
hasDigit = true;
else if (!Character.isLetterOrDigit(c))
hasSpecial = true;
}
if (!hasLower || !hasDigit || !hasSpecial) {
Toast.makeText(this, "A palavra-passe deve conter minúsculas, números e símbolos.", Toast.LENGTH_LONG)
.show();
return false;
}
return true;
}
}

View File

@@ -0,0 +1,56 @@
package com.example.pap_teste.models;
public class Mesa {
private String id;
private int numero;
private int capacidade;
private String estado;
public Mesa() {
// Default constructor required for calls to DataSnapshot.getValue(Mesa.class)
}
public Mesa(String id, int numero, int capacidade, String estado) {
this.id = id;
this.numero = numero;
this.capacidade = capacidade;
this.estado = estado;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
public int getCapacidade() {
return capacidade;
}
public void setCapacidade(int capacidade) {
this.capacidade = capacidade;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
@Override
public String toString() {
return "Mesa " + numero;
}
}

View File

@@ -0,0 +1,51 @@
package com.example.pap_teste.models;
public class Staff {
private String name;
private String zona;
private String mesa;
private String id;
public Staff(String name, String zona, String mesa, String id) {
this.name = name;
this.zona = zona;
this.mesa = mesa;
this.id = id;
}
public Staff() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getZona() {
return zona;
}
public void setZona(String zona) {
this.zona = zona;
}
public String getMesa() {
return mesa;
}
public void setMesa(String mesa) {
this.mesa = mesa;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}

View File

@@ -0,0 +1,73 @@
<?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/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddStaffActivity">
<EditText
android:id="@+id/nammeEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:hint="Name"
android:inputType="text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="@+id/zoneLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="@+id/nammeEditText"
app:layout_constraintStart_toStartOf="@+id/nammeEditText"
app:layout_constraintTop_toBottomOf="@+id/nammeEditText">
<Spinner
android:id="@+id/zonaSpinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="48dp" />
<Button
android:id="@+id/btnAddZone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />
</LinearLayout>
<LinearLayout
android:id="@+id/mesaLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="@+id/zoneLayout"
app:layout_constraintStart_toStartOf="@+id/zoneLayout"
app:layout_constraintTop_toBottomOf="@+id/zoneLayout">
<Spinner
android:id="@+id/mesaSpinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="48dp" />
</LinearLayout>
<Button
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -67,15 +67,13 @@
android:textSize="16sp"
android:textStyle="bold" />
<EditText
android:id="@+id/inputNomeStaff"
<Spinner
android:id="@+id/spinnerNomeStaff"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_marginTop="12dp"
android:background="@drawable/input_bg"
android:hint="Nome do funcionário"
android:inputType="textPersonName"
android:padding="12dp" />
android:padding="0dp" />
<Spinner
android:id="@+id/spinnerMesaStaff"
@@ -130,7 +128,21 @@
app:layout_constraintTop_toBottomOf="@id/txtListaStaffTitulo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
app:layout_constraintEnd_toEndOf="parent" >
</ListView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="32dp"
android:layout_marginBottom="32dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:srcCompat="@tools:sample/avatars" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -153,7 +153,8 @@
android:background="@drawable/input_bg"
android:hint="Email"
android:inputType="textEmailAddress"
android:padding="12dp" />
android:padding="12dp"
android:text="EstabelecimentoPap@gmail.com" />
<EditText
android:id="@+id/inputOwnerPhone"
@@ -207,7 +208,8 @@
android:background="@drawable/input_bg"
android:hint="Palavra-passe"
android:inputType="textPassword"
android:padding="12dp" />
android:padding="12dp"
android:text="PaP@P.1" />
<Button
android:id="@+id/btnFinalCriarConta"

View File

@@ -19,3 +19,13 @@ android.useAndroidX=true
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.defaults.buildfeatures.resvalues=true
android.sdk.defaultTargetSdkToCompileSdkIfUnset=false
android.enableAppCompileTimeRClass=false
android.usesSdkInManifest.disallowed=false
android.uniquePackageNames=false
android.dependency.useConstraints=true
android.r8.strictFullModeForKeepRules=false
android.r8.optimizedResourceShrinking=false
android.builtInKotlin=false
android.newDsl=false

View File

@@ -1,5 +1,5 @@
[versions]
agp = "8.13.2"
agp = "9.0.1"
junit = "4.13.2"
junitVersion = "1.3.0"
espressoCore = "3.7.0"
@@ -10,6 +10,7 @@ activity = "1.11.0"
constraintlayout = "2.2.1"
firebaseBom = "33.7.0"
googleServices = "4.4.2"
firebaseDatabase = "22.0.1"
[libraries]
junit = { group = "junit", name = "junit", version.ref = "junit" }
@@ -21,6 +22,7 @@ material = { group = "com.google.android.material", name = "material", version.r
activity = { group = "androidx.activity", name = "activity", version.ref = "activity" }
constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.ref = "firebaseBom" }
firebase-database = { group = "com.google.firebase", name = "firebase-database", version.ref = "firebaseDatabase" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }

View File

@@ -1,6 +1,6 @@
#Tue Jan 20 14:11:23 WET 2026
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists