Arquitetura Híbrida & Desempenho
Banco Relacional (MySQL)
Armazena permanentemente os registros financeiros, contas virtuais, cadastros de motoristas/passageiros, documentos, veículos e histórico final de viagens/entregas.
Firebase Realtime Database
Utilizado exclusivamente para recepção contínua de pulso GPS (a cada 3s) dos motoristas ativos e fila temporária de chamadas de 15 segundos. Reduz custos em até 75%.
Regras de Identificadores Únicos
- Usuários (Passageiros e Motoristas): Código numérico aleatório de 11 dígitos sem repetição (ex:
84920193841). - Serviços (Viagens e Entregas): Código numérico aleatório de 11 dígitos exclusivo para cada solicitação (ex:
10293847561). - Federal Pay (Conta Virtual): Identificador de 9 dígitos + dígito verificador único separado por hífen (ex:
394820192-8). Gerado no momento do cadastro de qualquer usuário.
Schema Completo do Banco de Dados (MySQL)
-- 1. TABELA DE USUÁRIOS
CREATE TABLE usr (
id INT AUTO_INCREMENT PRIMARY KEY,
cod_usr BIGINT UNIQUE NOT NULL, -- Identificador único de 11 dígitos
tip ENUM('pas', 'mot', 'adm') NOT NULL DEFAULT 'pas',
nom VARCHAR(100) NOT NULL,
eml VARCHAR(100) NOT NULL UNIQUE,
cel VARCHAR(20) NOT NULL UNIQUE,
cpf VARCHAR(14) NOT NULL UNIQUE,
fot VARCHAR(255) DEFAULT NULL,
sts ENUM('pen', 'ati', 'blo') NOT NULL DEFAULT 'pen',
tok_fcm VARCHAR(255) DEFAULT NULL,
dt_cad DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 2. TABELA DO MÓDULO FEDERAL PAY (CONTA VIRTUAL)
CREATE TABLE fed_pay (
id INT AUTO_INCREMENT PRIMARY KEY,
usr_id INT NOT NULL,
num_cta VARCHAR(9) UNIQUE NOT NULL, -- Identificador de 9 dígitos
dig_ver TINYINT NOT NULL, -- Dígito verificador (1 número)
sal_dis DECIMAL(10,2) NOT NULL DEFAULT 0.00,
sal_blo DECIMAL(10,2) NOT NULL DEFAULT 0.00,
chave_pix VARCHAR(100) DEFAULT NULL,
sts_cta ENUM('ati', 'blo', 'ana') DEFAULT 'ati',
dt_cri DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (usr_id) REFERENCES usr(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 3. TABELA DE DOCUMENTOS E BIOMETRIA DO MOTORISTA
CREATE TABLE mot_doc (
id INT AUTO_INCREMENT PRIMARY KEY,
usr_id INT NOT NULL,
cnh_num VARCHAR(20) NOT NULL,
cnh_vnc DATE NOT NULL,
cnh_url VARCHAR(255) NOT NULL,
crlv_url VARCHAR(255) NOT NULL,
bio_fac BOOLEAN DEFAULT FALSE,
sts_val ENUM('ana', 'apr', 'rej') DEFAULT 'ana',
FOREIGN KEY (usr_id) REFERENCES usr(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 4. TABELA DE VEÍCULOS
CREATE TABLE vei (
id INT AUTO_INCREMENT PRIMARY KEY,
usr_id INT NOT NULL,
plc VARCHAR(10) NOT NULL UNIQUE,
mod VARCHAR(50) NOT NULL,
cor VARCHAR(20) NOT NULL,
ano INT NOT NULL,
cat ENUM('pas', 'mot_ent', 'car_ent') NOT NULL DEFAULT 'pas',
FOREIGN KEY (usr_id) REFERENCES usr(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 5. TABELA DE VIAGENS E ENTREGAS
CREATE TABLE cor (
id INT AUTO_INCREMENT PRIMARY KEY,
cod_srv BIGINT UNIQUE NOT NULL, -- Identificador de serviço de 11 dígitos
pas_id INT NOT NULL,
mot_id INT DEFAULT NULL,
vei_id INT DEFAULT NULL,
tip ENUM('via', 'ent') NOT NULL DEFAULT 'via', -- Viagem ou Entrega
ori_end TEXT NOT NULL,
des_end TEXT NOT NULL,
ori_lat DECIMAL(10,8) NOT NULL,
ori_lng DECIMAL(11,8) NOT NULL,
des_lat DECIMAL(10,8) NOT NULL,
des_lng DECIMAL(11,8) NOT NULL,
dis_km DECIMAL(8,2) NOT NULL,
dur_min INT NOT NULL,
val_tot DECIMAL(10,2) NOT NULL,
tax_app DECIMAL(10,2) NOT NULL,
val_liq DECIMAL(10,2) NOT NULL,
pin_seg VARCHAR(4) NOT NULL,
sts ENUM('sol', 'ace', 'and', 'con', 'can') DEFAULT 'sol',
dt_sol DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (pas_id) REFERENCES usr(id),
FOREIGN KEY (mot_id) REFERENCES usr(id),
FOREIGN KEY (vei_id) REFERENCES vei(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 6. TRANSACIONAL FINANCEIRO DO FEDERAL PAY
CREATE TABLE fed_pay_tra (
id INT AUTO_INCREMENT PRIMARY KEY,
cta_ori_id INT DEFAULT NULL,
cta_des_id INT DEFAULT NULL,
cor_id INT DEFAULT NULL,
tip_mov ENUM('dep', 'saq', 'pag', 'rep', 'est') NOT NULL,
val DECIMAL(10,2) NOT NULL,
dt_mov DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cta_ori_id) REFERENCES fed_pay(id),
FOREIGN KEY (cta_des_id) REFERENCES fed_pay(id),
FOREIGN KEY (cor_id) REFERENCES cor(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Etapa 1: Inicialização Independente dos Apps
-
Criar os projetos Expo SDK 57 separados:
npx create-expo-app@latest federal-driver --template blank npx create-expo-app@latest federal-pro --template blank -
Instalar gerenciamento de rotas e safe area em ambos os projetos:
npx expo install expo-router react-native-safe-area-context react-native-screens expo-linking expo-constants expo-status-bar
Etapa 2: Instalação de Dependências e Módulos Nativos
Execute dentro das respectivas pastas de cada app (federal-driver e federal-pro):
# Instalação comum para ambos os apps
npx expo install react-native-maps react-native-maps-directions expo-location expo-image expo-notifications expo-local-authentication expo-image-picker expo-document-picker @react-native-async-storage/async-storage @react-navigation/native @react-navigation/bottom-tabs @react-navigation/drawer react-native-reanimated react-native-gesture-handler react-native-vector-icons react-native-safe-area-context
# Comunicação, Estado e Pagamentos
npm install firebase @stripe/stripe-react-native axios zustand
# EXCLUSIVO do Federal Driver (Background Location para GPS contínuo)
npx expo install expo-task-manager expo-background-fetch
Etapa 3: Arquitetura de Pastas e Módulo Federal Pay
Incorpore a pasta do Federal Pay na estrutura dos dois projetos para gestão de saldo e transferências internas:
src/
├── app/ # Rotas do Expo Router
├── assets/ # Imagens e ícones
├── components/ # Botões, Inputs, Modais
│ ├── maps/ # Renderização de mapas nativos
│ └── validation/ # Upload de CNH/CRLV e Biometria
├── screens/
│ ├── FederalPayScreen.jsx # 💳 Módulo da Carteira Virtual Federal Pay
│ ├── HomeScreen.jsx
│ ├── EntregaScreen.jsx
│ └── DeliveryScreen.jsx
├── config/ # Firebase, Axios e Stripe
├── hooks/ # Hooks customizados (useLocation, useAuth)
├── services/ # Chamadas de API ao backend Node.js / MySQL
├── store/ # Estados globais com Zustand
└── utils/ # Gerador de 11 dígitos, dígito verificador da conta e máscaras
Etapa 4: Funções para Identificadores Únicos em JS
Crie o arquivo src/utils/generators.js para garantir o cumprimento dos padrões numéricos solicitados:
// 1. Gera ID único de 11 dígitos para Usuários e Serviços
export function gerarIdOnzeDigitos() {
let resultado = '';
const primeiroDigito = Math.floor(Math.random() * 9) + 1; // Não começa com zero
resultado += primeiroDigito.toString();
for (let i = 0; i < 10; i++) {
resultado += Math.floor(Math.random() * 10).toString();
}
return parseInt(resultado, 10);
}
// 2. Gera Conta Federal Pay (9 dígitos + Dígito Verificador de 1 número)
export function gerarContaFederalPay() {
let numeroConta = '';
for (let i = 0; i < 9; i++) {
numeroConta += Math.floor(Math.random() * 10).toString();
}
// Algoritmo de Módulo 11 para criação do dígito verificador
let soma = 0;
for (let i = 0; i < 9; i++) {
soma += parseInt(numeroConta.charAt(i)) * (10 - i);
}
const resto = soma % 11;
let digitoVerificador = 11 - resto;
if (digitoVerificador >= 10) digitoVerificador = 0;
return {
numCta: numeroConta,
digVer: digitoVerificador,
formatada: `${numeroConta}-${digitoVerificador}`
};
}
Etapa 5: Geração de Build e Publicação nas Lojas
-
Configuração do EAS Build CLI:
npm install -g eas-cli eas login -
Build de Teste e Desenvolvimento:
eas build --profile development --platform all -
Build de Produção e Submissão:
eas build --platform all --profile production eas submit --platform all