webmoney/backend/app/Services/UserSetupService.php

311 lines
17 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
/**
* Serviço para configurar dados iniciais de novos usuários
* Cria categorias, subcategorias e keywords padrão
*/
class UserSetupService
{
private $userId;
private $now;
private $categoryId = 0;
/**
* Criar todas as categorias padrão para um novo usuário
*/
public function createDefaultCategories(int $userId): void
{
$this->userId = $userId;
$this->now = Carbon::now();
$this->categoryId = 0;
// ========================================
// RECEITAS (income)
// ========================================
// 1. Salário e Trabalho
$salario = $this->createCategory('Salário e Trabalho', 'income', 'Rendimentos do trabalho', '#10B981', 'bi-briefcase');
$this->createSubcategories($salario, [
['name' => 'Salário Líquido', 'keywords' => ['NOMINA', 'SALARIO', 'SUELDO', 'PAGO NOMINA']],
['name' => 'Horas Extras', 'keywords' => ['HORAS EXTRA', 'OVERTIME']],
['name' => 'Bônus/Bonus', 'keywords' => ['BONUS', 'BONO', 'GRATIFICACION']],
['name' => 'Comissões', 'keywords' => ['COMISION', 'COMISSAO']],
['name' => 'Dietas/Ajudas', 'keywords' => ['DIETA', 'AJUDA CUSTO', 'VIATICOS']],
['name' => 'Freelance', 'keywords' => ['FREELANCE', 'AUTONOMO', 'PROYECTO']],
]);
// 2. Investimentos
$investimentos = $this->createCategory('Investimentos', 'income', 'Rendimentos de investimentos', '#059669', 'bi-graph-up-arrow');
$this->createSubcategories($investimentos, [
['name' => 'Dividendos', 'keywords' => ['DIVIDENDO', 'DIVIDEND']],
['name' => 'Juros Poupança', 'keywords' => ['INTERESES', 'JUROS', 'RENDIMIENTO']],
['name' => 'Aluguel Recebido', 'keywords' => ['ALQUILER RECIBIDO', 'RENTA RECIBIDA']],
['name' => 'Venda de Ativos', 'keywords' => ['VENTA ACCIONES', 'VENDA ATIVO']],
]);
// 3. Reembolsos
$reembolsos = $this->createCategory('Reembolsos', 'income', 'Devoluções e reembolsos', '#14B8A6', 'bi-arrow-return-left');
$this->createSubcategories($reembolsos, [
['name' => 'Devolução Compras', 'keywords' => ['DEVOLUCION', 'DEVOLUÇÃO', 'REEMBOLSO', 'REFUND']],
['name' => 'Reembolso Despesas', 'keywords' => ['REEMBOLSO GASTOS', 'EXPENSE REFUND']],
['name' => 'Estorno', 'keywords' => ['ESTORNO', 'ANULACION', 'CANCELACION']],
]);
// 4. Transferências Recebidas
$transRecebidas = $this->createCategory('Transferências Recebidas', 'income', 'Dinheiro recebido de terceiros', '#0D9488', 'bi-box-arrow-in-down');
$this->createSubcategories($transRecebidas, [
['name' => 'De Familiares', 'keywords' => []],
['name' => 'De Amigos', 'keywords' => []],
['name' => 'Bizum Recebido', 'keywords' => ['BIZUM RECIBIDO', 'BIZUM A FAVOR']],
]);
// 5. Outros Rendimentos
$outrosRend = $this->createCategory('Outros Rendimentos', 'income', 'Outras fontes de renda', '#047857', 'bi-cash-stack');
$this->createSubcategories($outrosRend, [
['name' => 'Prêmios/Sorteios', 'keywords' => ['PREMIO', 'SORTEO', 'LOTERIA']],
['name' => 'Venda Usados', 'keywords' => ['WALLAPOP', 'VINTED', 'MILANUNCIOS']],
['name' => 'Cashback', 'keywords' => ['CASHBACK', 'RECOMPENSA']],
]);
// ========================================
// DESPESAS (expense)
// ========================================
// 6. Moradia
$moradia = $this->createCategory('Moradia', 'expense', 'Gastos com casa e moradia', '#EF4444', 'bi-house-door');
$this->createSubcategories($moradia, [
['name' => 'Aluguel', 'keywords' => ['ALQUILER', 'RENTA MENSUAL', 'ARRENDAMIENTO']],
['name' => 'Hipoteca', 'keywords' => ['HIPOTECA', 'MORTGAGE', 'PRESTAMO VIVIENDA']],
['name' => 'Condomínio', 'keywords' => ['COMUNIDAD', 'GASTOS COMUNES', 'CONDOMINIO']],
['name' => 'Seguro Casa', 'keywords' => ['SEGURO HOGAR', 'SEGURO VIVIENDA']],
['name' => 'IPTU/IBI', 'keywords' => ['IBI', 'IMPUESTO BIENES INMUEBLES']],
['name' => 'Manutenção Casa', 'keywords' => ['REPARACION', 'MANTENIMIENTO HOGAR']],
]);
// 7. Serviços/Utilities
$servicos = $this->createCategory('Serviços/Utilities', 'expense', 'Contas de serviços básicos', '#DC2626', 'bi-lightning-charge');
$this->createSubcategories($servicos, [
['name' => 'Eletricidade', 'keywords' => ['IBERDROLA', 'ENDESA', 'NATURGY', 'ELECTRICIDAD', 'LUZ']],
['name' => 'Gás', 'keywords' => ['GAS NATURAL', 'NEDGIA', 'MADRILEÑA DE GAS']],
['name' => 'Água', 'keywords' => ['CANAL ISABEL II', 'AGUA', 'CICLO AGUA']],
['name' => 'Internet/Fibra', 'keywords' => ['MOVISTAR', 'VODAFONE', 'ORANGE', 'MASMOVIL', 'DIGI', 'FIBRA', 'INTERNET']],
['name' => 'Telefone Móvel', 'keywords' => ['TELEFONICA', 'MOVIL', 'MOBILE', 'CELULAR']],
['name' => 'TV/Streaming', 'keywords' => ['NETFLIX', 'HBO', 'DISNEY', 'AMAZON PRIME', 'SPOTIFY', 'YOUTUBE']],
]);
// 8. Alimentação
$alimentacao = $this->createCategory('Alimentação', 'expense', 'Gastos com comida e bebida', '#F97316', 'bi-cart3');
$this->createSubcategories($alimentacao, [
['name' => 'Supermercado', 'keywords' => ['MERCADONA', 'CARREFOUR', 'DIA', 'LIDL', 'ALDI', 'ALCAMPO', 'HIPERCOR', 'AHORRAMAS', 'SUPERMERCADO', 'EROSKI']],
['name' => 'Padaria/Confeitaria', 'keywords' => ['PANADERIA', 'PASTELERIA', 'HORNO', 'BAKERY']],
['name' => 'Açougue/Peixaria', 'keywords' => ['CARNICERIA', 'PESCADERIA', 'BUTCHER']],
['name' => 'Frutas/Verduras', 'keywords' => ['FRUTERIA', 'VERDULERIA', 'MERCADO']],
['name' => 'Delivery Comida', 'keywords' => ['GLOVO', 'UBER EATS', 'JUST EAT', 'DELIVEROO']],
]);
// 9. Restaurantes e Lazer
$restaurantes = $this->createCategory('Restaurantes e Lazer', 'expense', 'Comer fora e entretenimento', '#EA580C', 'bi-cup-straw');
$this->createSubcategories($restaurantes, [
['name' => 'Restaurantes', 'keywords' => ['RESTAURANTE', 'RESTAURANT', 'ASADOR', 'TABERNA']],
['name' => 'Cafés/Bares', 'keywords' => ['CAFE', 'BAR', 'CERVECERIA', 'CAFETERIA', 'STARBUCKS', 'TIM HORTONS']],
['name' => 'Fast Food', 'keywords' => ['MCDONALDS', 'BURGER KING', 'KFC', 'TELEPIZZA', 'DOMINOS', 'FIVE GUYS']],
['name' => 'Cinema/Teatro', 'keywords' => ['CINESA', 'YELMO', 'KINEPOLIS', 'TEATRO', 'CINEMA']],
['name' => 'Eventos/Shows', 'keywords' => ['TICKETMASTER', 'ENTRADAS', 'CONCIERTO', 'EVENTO']],
['name' => 'Museus/Cultura', 'keywords' => ['MUSEO', 'EXPOSICION', 'CULTURA']],
]);
// 10. Transporte
$transporte = $this->createCategory('Transporte', 'expense', 'Gastos com deslocamento', '#F59E0B', 'bi-car-front');
$this->createSubcategories($transporte, [
['name' => 'Combustível', 'keywords' => ['REPSOL', 'CEPSA', 'BP', 'SHELL', 'GASOLINERA', 'GASOLINA', 'DIESEL', 'COMBUSTIBLE']],
['name' => 'Metro/Ônibus', 'keywords' => ['METRO MADRID', 'EMT', 'CRTM', 'ABONO TRANSPORTE', 'TARJETA TRANSPORTE']],
['name' => 'Táxi/Uber', 'keywords' => ['UBER', 'CABIFY', 'FREE NOW', 'TAXI', 'BOLT']],
['name' => 'Estacionamento', 'keywords' => ['PARKING', 'APARCAMIENTO', 'ESTACIONAMIENTO', 'SER', 'EMPARK']],
['name' => 'Pedágios', 'keywords' => ['PEAJE', 'AUTOPISTA', 'VIA T']],
['name' => 'Manutenção Carro', 'keywords' => ['TALLER', 'MECANICO', 'REVISION', 'ITV', 'NEUMATICO', 'MIDAS', 'NORAUTO']],
['name' => 'Seguro Carro', 'keywords' => ['SEGURO AUTO', 'SEGURO COCHE', 'MAPFRE', 'LINEA DIRECTA', 'MUTUA']],
['name' => 'Trem/AVE', 'keywords' => ['RENFE', 'AVE', 'CERCANIAS', 'TREN', 'OUIGO', 'IRYO']],
['name' => 'Aluguel Veículos', 'keywords' => ['RENT A CAR', 'ENTERPRISE', 'HERTZ', 'AVIS', 'EUROPCAR']],
]);
// 11. Saúde
$saude = $this->createCategory('Saúde', 'expense', 'Gastos médicos e bem-estar', '#EC4899', 'bi-heart-pulse');
$this->createSubcategories($saude, [
['name' => 'Farmácia', 'keywords' => ['FARMACIA', 'PHARMACY', 'MEDICAMENTO', 'PARAFARMACIA']],
['name' => 'Médico/Consulta', 'keywords' => ['CLINICA', 'HOSPITAL', 'CONSULTA MEDICA', 'SANITAS', 'ADESLAS', 'ASISA']],
['name' => 'Dentista', 'keywords' => ['DENTISTA', 'DENTAL', 'CLINICA DENTAL', 'VITALDENT']],
['name' => 'Ótica', 'keywords' => ['OPTICA', 'GAFAS', 'LENTILLAS', 'GENERAL OPTICA', 'MULTIOPTICAS']],
['name' => 'Seguro Saúde', 'keywords' => ['SEGURO MEDICO', 'SEGURO SALUD', 'MUTUA', 'DKV']],
['name' => 'Academia/Gym', 'keywords' => ['GYM', 'GIMNASIO', 'FITNESS', 'BASIC FIT', 'MCFIT', 'METROPOLITAN']],
['name' => 'Psicólogo/Terapia', 'keywords' => ['PSICOLOGO', 'TERAPIA', 'PSIQUIATRA']],
]);
// 12. Compras/Shopping
$compras = $this->createCategory('Compras/Shopping', 'expense', 'Compras diversas', '#8B5CF6', 'bi-bag');
$this->createSubcategories($compras, [
['name' => 'Roupas/Calçados', 'keywords' => ['ZARA', 'MANGO', 'HM', 'PRIMARK', 'PULL BEAR', 'BERSHKA', 'MASSIMO DUTTI', 'FOOTLOCKER']],
['name' => 'Eletrônicos', 'keywords' => ['MEDIA MARKT', 'FNAC', 'PC COMPONENTES', 'APPLE STORE', 'WORTEN']],
['name' => 'Casa/Decoração', 'keywords' => ['IKEA', 'LEROY MERLIN', 'ZARA HOME', 'MAISONS DU MONDE']],
['name' => 'Amazon/Online', 'keywords' => ['AMAZON', 'ALIEXPRESS', 'EBAY', 'WISH']],
['name' => 'Presentes', 'keywords' => ['REGALO', 'PRESENTE', 'GIFT']],
['name' => 'Cosméticos/Beleza', 'keywords' => ['SEPHORA', 'PRIMOR', 'DRUNI', 'PERFUMERIA', 'RITUALS']],
]);
// 13. Educação
$educacao = $this->createCategory('Educação', 'expense', 'Investimento em conhecimento', '#6366F1', 'bi-mortarboard');
$this->createSubcategories($educacao, [
['name' => 'Cursos/Formação', 'keywords' => ['CURSO', 'FORMACION', 'UDEMY', 'COURSERA', 'DOMESTIKA']],
['name' => 'Livros/Material', 'keywords' => ['LIBRERIA', 'CASA DEL LIBRO', 'LIBRO', 'KINDLE']],
['name' => 'Escola/Colégio', 'keywords' => ['COLEGIO', 'ESCUELA', 'MATRICULA']],
['name' => 'Idiomas', 'keywords' => ['ACADEMIA IDIOMAS', 'ENGLISH', 'VAUGHAN', 'WALL STREET']],
]);
// 14. Finanças
$financas = $this->createCategory('Finanças', 'expense', 'Custos financeiros', '#3B82F6', 'bi-bank');
$this->createSubcategories($financas, [
['name' => 'Taxas Bancárias', 'keywords' => ['COMISION', 'MANTENIMIENTO CUENTA', 'TASA BANCARIA']],
['name' => 'Juros/Empréstimos', 'keywords' => ['INTERESES', 'PRESTAMO', 'CREDITO']],
['name' => 'Cartão de Crédito', 'keywords' => ['PAGO TARJETA', 'CUOTA TARJETA']],
['name' => 'Impostos', 'keywords' => ['HACIENDA', 'IRPF', 'IVA', 'IMPUESTO', 'AGENCIA TRIBUTARIA']],
['name' => 'Seguros Gerais', 'keywords' => ['SEGURO', 'POLIZA', 'INSURANCE']],
]);
// 15. Lazer/Hobbies
$lazer = $this->createCategory('Lazer/Hobbies', 'expense', 'Atividades recreativas', '#A855F7', 'bi-controller');
$this->createSubcategories($lazer, [
['name' => 'Jogos/Games', 'keywords' => ['PLAYSTATION', 'XBOX', 'STEAM', 'NINTENDO', 'GAME']],
['name' => 'Esportes', 'keywords' => ['DECATHLON', 'SPRINTER', 'DEPORTE', 'FUTBOL', 'PADEL']],
['name' => 'Viagens', 'keywords' => ['BOOKING', 'AIRBNB', 'HOTEL', 'VUELING', 'RYANAIR', 'IBERIA', 'VUELO']],
['name' => 'Assinaturas', 'keywords' => ['SUSCRIPCION', 'MEMBERSHIP', 'PREMIUM']],
]);
// 16. Pessoal/Outros
$pessoal = $this->createCategory('Pessoal/Outros', 'expense', 'Gastos pessoais diversos', '#64748B', 'bi-person');
$this->createSubcategories($pessoal, [
['name' => 'Cabeleireiro/Barbeiro', 'keywords' => ['PELUQUERIA', 'BARBERIA', 'CORTE PELO']],
['name' => 'Lavanderia', 'keywords' => ['LAVANDERIA', 'TINTORERIA', 'LAUNDRY']],
['name' => 'Pets/Animais', 'keywords' => ['VETERINARIO', 'MASCOTA', 'TIENDANIMAL', 'KIWOKO']],
['name' => 'Doações', 'keywords' => ['DONACION', 'CARIDAD', 'ONG']],
['name' => 'Outros', 'keywords' => []],
]);
// 17. Transferências Enviadas
$transEnviadas = $this->createCategory('Transferências Enviadas', 'expense', 'Dinheiro enviado a terceiros', '#475569', 'bi-box-arrow-up');
$this->createSubcategories($transEnviadas, [
['name' => 'Para Familiares', 'keywords' => []],
['name' => 'Para Amigos', 'keywords' => []],
['name' => 'Bizum Enviado', 'keywords' => ['BIZUM ENVIADO', 'BIZUM A FAVOR DE']],
['name' => 'Remessa Internacional', 'keywords' => ['WESTERN UNION', 'REMESA', 'TRANSFERWISE', 'WISE']],
]);
// ========================================
// TRANSFERÊNCIAS (transfer)
// ========================================
// 18. Transferências Entre Contas
$transfer = $this->createCategory('Transferências Entre Contas', 'transfer', 'Movimentação entre contas próprias', '#0EA5E9', 'bi-arrow-left-right');
$this->createSubcategories($transfer, [
['name' => 'Entre Contas Correntes', 'keywords' => ['TRANSFERENCIA PROPIA', 'TRASPASO']],
['name' => 'Para Poupança', 'keywords' => ['AHORRO', 'POUPANCA']],
['name' => 'Para Investimentos', 'keywords' => ['INVERSION', 'BROKER', 'TRADE REPUBLIC', 'DEGIRO']],
['name' => 'Saque/Depósito', 'keywords' => ['CAJERO', 'ATM', 'RETIRADA', 'INGRESO EFECTIVO']],
]);
}
private function createCategory(string $name, string $type, string $description, string $color, string $icon): array
{
$this->categoryId++;
DB::table('categories')->insert([
'user_id' => $this->userId,
'parent_id' => null,
'name' => $name,
'type' => $type,
'description' => $description,
'color' => $color,
'icon' => $icon,
'order' => $this->categoryId,
'is_active' => true,
'is_system' => false,
'created_at' => $this->now,
'updated_at' => $this->now,
]);
return ['id' => DB::getPdo()->lastInsertId(), 'type' => $type];
}
private function createSubcategories(array $parent, array $subcategories): void
{
$parentId = $parent['id'];
$parentType = $parent['type'];
foreach ($subcategories as $index => $sub) {
$this->categoryId++;
DB::table('categories')->insert([
'user_id' => $this->userId,
'parent_id' => $parentId,
'name' => $sub['name'],
'type' => $parentType,
'description' => null,
'color' => '#6B7280',
'icon' => 'bi-tag',
'order' => $index + 1,
'is_active' => true,
'is_system' => false,
'created_at' => $this->now,
'updated_at' => $this->now,
]);
$subcategoryId = DB::getPdo()->lastInsertId();
// Adicionar keywords
if (!empty($sub['keywords'])) {
foreach ($sub['keywords'] as $keyword) {
DB::table('category_keywords')->insert([
'category_id' => $subcategoryId,
'keyword' => strtolower($keyword),
'is_case_sensitive' => false,
'is_active' => true,
'created_at' => $this->now,
'updated_at' => $this->now,
]);
}
}
}
}
/**
* Criar centro de custo padrão para novo usuário
*/
public function createDefaultCostCenter(int $userId): void
{
$now = Carbon::now();
DB::table('cost_centers')->insert([
'user_id' => $userId,
'name' => 'Principal',
'description' => 'Centro de custo padrão',
'color' => '#3B82F6',
'is_active' => true,
'is_system' => true,
'created_at' => $now,
'updated_at' => $now,
]);
}
/**
* Configurar tudo para um novo usuário
*/
public function setupNewUser(int $userId): void
{
$this->createDefaultCategories($userId);
$this->createDefaultCostCenter($userId);
}
}