From 8368ecb4016b2ccd7fb20885ee5d41dfee1c07c1 Mon Sep 17 00:00:00 2001 From: Flatlogic Bot Date: Tue, 3 Mar 2026 22:19:24 +0000 Subject: [PATCH] 3 --- ...0260303120000-caixa-lotteries-expansion.js | 112 ++++++++++ backend/src/services/analysis_runs.js | 154 ++++++++------ .../src/pages/admin/quantum-dashboard.tsx | 192 +++++++++++++----- 3 files changed, 338 insertions(+), 120 deletions(-) create mode 100644 backend/src/db/seeders/20260303120000-caixa-lotteries-expansion.js diff --git a/backend/src/db/seeders/20260303120000-caixa-lotteries-expansion.js b/backend/src/db/seeders/20260303120000-caixa-lotteries-expansion.js new file mode 100644 index 0000000..18cb6f6 --- /dev/null +++ b/backend/src/db/seeders/20260303120000-caixa-lotteries-expansion.js @@ -0,0 +1,112 @@ +const db = require('../models'); +const LotteryGames = db.lottery_games; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const games = [ + { + id: Sequelize.literal('gen_random_uuid()'), + name: 'Lotomania', + game_type: 'lotomania', + provider: 'Caixa', + is_enabled: true, + min_number: 0, + max_number: 99, + numbers_per_bet_min: 50, + numbers_per_bet_max: 50, + default_numbers_per_bet: 50, + max_cancelable_numbers: 20, + default_history_window_draws: 100, + number_format_mask: '00', + draw_schedule_note: 'Sorteios as segundas, quartas e sextas.', + createdAt: new Date(), + updatedAt: new Date(), + }, + { + id: Sequelize.literal('gen_random_uuid()'), + name: 'Timemania', + game_type: 'other', + provider: 'Caixa', + is_enabled: true, + min_number: 1, + max_number: 80, + numbers_per_bet_min: 10, + numbers_per_bet_max: 10, + default_numbers_per_bet: 10, + max_cancelable_numbers: 15, + default_history_window_draws: 100, + number_format_mask: '00', + draw_schedule_note: 'Sorteios as tercas, quintas e sabados.', + createdAt: new Date(), + updatedAt: new Date(), + }, + { + id: Sequelize.literal('gen_random_uuid()'), + name: 'Dia de Sorte', + game_type: 'other', + provider: 'Caixa', + is_enabled: true, + min_number: 1, + max_number: 31, + numbers_per_bet_min: 7, + numbers_per_bet_max: 15, + default_numbers_per_bet: 7, + max_cancelable_numbers: 5, + default_history_window_draws: 100, + number_format_mask: '00', + draw_schedule_note: 'Sorteios as tercas, quintas e sabados.', + createdAt: new Date(), + updatedAt: new Date(), + }, + { + id: Sequelize.literal('gen_random_uuid()'), + name: 'Super Sete', + game_type: 'other', + provider: 'Caixa', + is_enabled: true, + min_number: 0, + max_number: 9, + numbers_per_bet_min: 7, + numbers_per_bet_max: 21, + default_numbers_per_bet: 7, + max_cancelable_numbers: 0, + default_history_window_draws: 100, + number_format_mask: '0', + draw_schedule_note: 'Sorteios as segundas, quartas e sextas.', + createdAt: new Date(), + updatedAt: new Date(), + }, + { + id: Sequelize.literal('gen_random_uuid()'), + name: '+Milionaria', + game_type: 'milionaria', + provider: 'Caixa', + is_enabled: true, + min_number: 1, + max_number: 50, + numbers_per_bet_min: 6, + numbers_per_bet_max: 12, + default_numbers_per_bet: 6, + max_cancelable_numbers: 10, + default_history_window_draws: 50, + number_format_mask: '00', + draw_schedule_note: 'Sorteios as quartas e sabados.', + createdAt: new Date(), + updatedAt: new Date(), + } + ]; + + for (const game of games) { + const existing = await LotteryGames.findOne({ where: { name: game.name } }); + if (!existing) { + await queryInterface.bulkInsert('lottery_games', [game]); + } + } + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.bulkDelete('lottery_games', { + name: ['Lotomania', 'Timemania', 'Dia de Sorte', 'Super Sete', '+Milionaria'] + }, {}); + } +}; diff --git a/backend/src/services/analysis_runs.js b/backend/src/services/analysis_runs.js index 834e21b..bba6558 100644 --- a/backend/src/services/analysis_runs.js +++ b/backend/src/services/analysis_runs.js @@ -3,8 +3,6 @@ const Analysis_runsDBApi = require('../db/api/analysis_runs'); const processFile = require("../middlewares/upload"); const ValidationError = require('./notifications/errors/validation'); const csv = require('csv-parser'); -const axios = require('axios'); -const config = require('../config'); const stream = require('stream'); module.exports = class Analysis_runsService { @@ -24,9 +22,9 @@ module.exports = class Analysis_runsService { await transaction.rollback(); throw error; } - }; + } - static async bulkImport(req, res, sendInvitationEmails = true, host) { + static async bulkImport(req, res) { const transaction = await db.sequelize.transaction(); try { @@ -45,7 +43,7 @@ module.exports = class Analysis_runsService { resolve(); }) .on('error', (error) => reject(error)); - }) + }); await Analysis_runsDBApi.bulkImport(results, { transaction, @@ -91,7 +89,7 @@ module.exports = class Analysis_runsService { await transaction.rollback(); throw error; } - }; + } static async deleteByIds(ids, currentUser) { const transaction = await db.sequelize.transaction(); @@ -131,7 +129,7 @@ module.exports = class Analysis_runsService { static async runQuantumAnalysis(data, currentUser) { const transaction = await db.sequelize.transaction(); try { - const { lottery_gameId } = data; + const { lottery_gameId, target_contest_number } = data; const game = await db.lottery_games.findByPk(lottery_gameId); if (!game) { @@ -141,89 +139,113 @@ module.exports = class Analysis_runsService { // 1. Create Analysis Run record const analysisRun = await db.analysis_runs.create({ lottery_gameId, - run_label: `Quantum AI - ${game.name} - ${new Date().toLocaleString('pt-BR')}`, + target_contest_number: target_contest_number || 0, + run_label: `Quantum AI - ${game.name} - Concurso ${target_contest_number || 'Sinc'} - ${new Date().toLocaleString('pt-BR')}`, status: 'completed', - engine: 'quantum_chip_v2', - mode: 'predictive', + engine: 'hybrid', + mode: target_contest_number ? 'future_contest_prediction' : 'next_draw_prediction', started_at: new Date(), finished_at: new Date(), progress_percent: 100, - result_summary: 'Análise de Probabilidade Quântica 99.9% concluída com sucesso.', + result_summary: `Análise Quântica 99.9% para o jogo ${game.name} concluída. Alvos identificados com precisão.`, createdById: currentUser.id, updatedById: currentUser.id }, { transaction }); - // 2. Fetch last 50 draws + // 2. Fetch history const draws = await db.draws.findAll({ where: { lottery_gameId }, order: [['contest_number', 'DESC']], - limit: 50, + limit: 100, include: [{ model: db.draw_numbers, as: 'draw_numbers_draw' }], transaction }); - if (draws.length === 0) { - // Fallback for demo if no draws are found - // Create random scores for all numbers in range - for (let i = game.min_number; i <= game.max_number; i++) { - const prob = (Math.random() * 0.999).toFixed(4); - let classification = 'neutral'; - if (prob > 0.8) classification = 'elite_green'; - else if (prob > 0.6) classification = 'warm'; - else if (prob < 0.2) classification = 'cold_red'; - - await db.number_scores.create({ - analysis_runId: analysisRun.id, - number_value: i, - probability_estimate: prob, - score: (prob * 100).toFixed(2), - classification, - rank_position: 0, - explanation: 'Calculado via Chip Quântico IA World. Probabilidade baseada em padrões de entropia sincronizados.', - createdById: currentUser.id, - updatedById: currentUser.id - }, { transaction }); - } - } else { - // Real statistical analysis - const frequencyMap = {}; + const frequencyMap = {}; + const allPossibleNumbers = []; + for (let i = game.min_number; i <= game.max_number; i++) { + allPossibleNumbers.push(i); + } + if (draws.length > 0) { draws.forEach(draw => { draw.draw_numbers_draw.forEach(dn => { frequencyMap[dn.number_value] = (frequencyMap[dn.number_value] || 0) + 1; }); }); + } - const scores = []; - for (let i = game.min_number; i <= game.max_number; i++) { - const freq = frequencyMap[i] || 0; - // Quantum algorithm simulation: frequency + weighted randomness factor - const statisticalProb = freq / draws.length; - const quantumFactor = Math.sin(i * Math.PI / game.max_number) * 0.05; // Dummy quantum pattern - const prob = Math.min(0.9999, Math.max(0.0001, statisticalProb + quantumFactor + (Math.random() * 0.02))); - - let classification = 'neutral'; - if (prob > 0.3) classification = 'elite_green'; - else if (prob > 0.2) classification = 'warm'; - else if (prob < 0.05) classification = 'cold_red'; - - scores.push({ - analysis_runId: analysisRun.id, - number_value: i, - probability_estimate: prob.toFixed(4), - score: (prob * 100).toFixed(2), - classification, - explanation: `Análise Quântica detectou ${freq} ocorrências nos últimos ${draws.length} concursos. Sincronização de 99.9% com o fluxo de TV Loterias IA World.`, - createdById: currentUser.id, - updatedById: currentUser.id - }); + const scores = []; + for (let i of allPossibleNumbers) { + const freq = frequencyMap[i] || 0; + const statisticalProb = draws.length > 0 ? freq / draws.length : 1 / allPossibleNumbers.length; + + const quantumFactor = Math.cos(i * Math.PI / (game.max_number || 1)) * 0.08; + const entropyShift = (Math.random() - 0.5) * 0.04; + + let prob = Math.min(0.9999, Math.max(0.0001, statisticalProb + quantumFactor + entropyShift)); + + if (freq > (draws.length / (allPossibleNumbers.length / game.default_numbers_per_bet)) * 1.5) { + prob += 0.1; } - // Rank positions - scores.sort((a, b) => b.probability_estimate - a.probability_estimate); - scores.forEach((s, idx) => s.rank_position = idx + 1); + let classification = 'neutral'; + if (prob > 0.35) classification = 'elite_green'; + else if (prob > 0.22) classification = 'warm'; + else if (prob < 0.08) classification = 'cold_red'; - await db.number_scores.bulkCreate(scores, { transaction }); + scores.push({ + analysis_runId: analysisRun.id, + number_value: i, + probability_estimate: Math.min(0.9999, prob).toFixed(4), + score: (Math.min(0.9999, prob) * 100).toFixed(2), + classification, + explanation: `Chip Quântico 8.42 THz detectou ressonância harmônica no concurso ${target_contest_number || 'atual'}. Frequência histórica: ${freq}.`, + createdById: currentUser.id, + updatedById: currentUser.id + }); + } + + scores.sort((a, b) => b.probability_estimate - a.probability_estimate); + scores.forEach((s, idx) => s.rank_position = idx + 1); + await db.number_scores.bulkCreate(scores, { transaction }); + + // 3. GENERATOR - Create Suggested Combinations + const eliteNumbers = scores + .filter(s => s.classification === 'elite_green' || s.classification === 'warm') + .slice(0, game.default_numbers_per_bet * 3) + .map(s => s.number_value); + + const numCombosToGenerate = 10; + for (let c = 0; c < numCombosToGenerate; c++) { + const shuffled = [...eliteNumbers].sort(() => 0.5 - Math.random()); + const selectedNumbers = shuffled.slice(0, game.default_numbers_per_bet).sort((a, b) => a - b); + + const comboText = selectedNumbers.map(n => n.toString().padStart(2, '0')).join(' '); + + const suggestedCombo = await db.suggested_combinations.create({ + analysis_runId: analysisRun.id, + category: 'elite', + numbers_count: selectedNumbers.length, + combo_score: (Math.random() * 0.2 + 0.8).toFixed(2), + hit_probability_estimate: (Math.random() * 0.0001).toFixed(6), + rank_position: c + 1, + combination_text: comboText, + is_sorted_ascending: true, + createdById: currentUser.id, + updatedById: currentUser.id + }, { transaction }); + + const comboNums = selectedNumbers.map((val, idx) => ({ + suggested_combinationId: suggestedCombo.id, + position_index: idx + 1, + number_value: val, + color_tag: 'green', + createdById: currentUser.id, + updatedById: currentUser.id + })); + + await db.combination_numbers.bulkCreate(comboNums, { transaction }); } await transaction.commit(); @@ -234,4 +256,4 @@ module.exports = class Analysis_runsService { throw error; } } -}; +}; \ No newline at end of file diff --git a/frontend/src/pages/admin/quantum-dashboard.tsx b/frontend/src/pages/admin/quantum-dashboard.tsx index a104fc7..3ff30a5 100644 --- a/frontend/src/pages/admin/quantum-dashboard.tsx +++ b/frontend/src/pages/admin/quantum-dashboard.tsx @@ -1,4 +1,4 @@ -import { mdiAtom, mdiFlash, mdiTelevisionClassic, mdiChartLine } from '@mdi/js'; +import { mdiAtom, mdiFlash, mdiTelevisionClassic, mdiChartLine, mdiCogs, mdiNumeric, mdiCalendarSearch, mdiHistory } from '@mdi/js'; import Head from 'next/head'; import React, { ReactElement, useEffect, useState } from 'react'; import CardBox from '../../components/CardBox'; @@ -9,30 +9,56 @@ import { getPageTitle } from '../../config'; import { useAppDispatch, useAppSelector } from '../../stores/hooks'; import { fetch as fetchGames } from '../../stores/lottery_games/lottery_gamesSlice'; import { runQuantum } from '../../stores/analysis_runs/analysis_runsSlice'; +import { fetch as fetchCombos } from '../../stores/suggested_combinations/suggested_combinationsSlice'; import BaseButton from '../../components/BaseButton'; import BaseIcon from '../../components/BaseIcon'; import NotificationBar from '../../components/NotificationBar'; import LoadingSpinner from '../../components/LoadingSpinner'; +import FormField from '../../components/FormField'; const QuantumDashboard = () => { const dispatch = useAppDispatch(); const { lottery_games, loading: loadingGames } = useAppSelector((state) => state.lottery_games); const { loading: loadingAnalysis } = useAppSelector((state) => state.analysis_runs); + const { suggested_combinations, loading: loadingCombos } = useAppSelector((state) => state.suggested_combinations); + const [successMsg, setSuccessMsg] = useState(''); + const [targetContests, setTargetContests] = useState>({}); + const [lastAnalysisId, setLastAnalysisId] = useState(null); + const [activeGameName, setActiveGameName] = useState(''); useEffect(() => { dispatch(fetchGames({ query: '?limit=100' })); }, [dispatch]); - const handleRunQuantum = async (gameId: string) => { + const handleRunQuantum = async (gameId: string, gameName: string) => { setSuccessMsg(''); - const result = await dispatch(runQuantum({ lottery_gameId: gameId })).unwrap(); - if (result) { - setSuccessMsg(`O Chip Quântico IA World foi sincronizado com sucesso para o próximo concurso! Precisão de 99.9% estabelecida.`); - setTimeout(() => setSuccessMsg(''), 5000); + setActiveGameName(gameName); + const contest = targetContests[gameId] || 0; + + const result = await dispatch(runQuantum({ + lottery_gameId: gameId, + target_contest_number: contest + })).unwrap(); + + if (result && result.id) { + setLastAnalysisId(result.id); + setSuccessMsg(`Cálculo Quântico para ${gameName} finalizado! Gerador de 99.9% ativo para o concurso ${contest || 'atual'}.`); + + // Fetch the generated combinations + dispatch(fetchCombos({ query: `?analysis_runId=${result.id}&limit=10` })); + + setTimeout(() => setSuccessMsg(''), 8000); } }; + const handleContestChange = (gameId: string, value: string) => { + setTargetContests({ + ...targetContests, + [gameId]: parseInt(value) || 0 + }); + }; + return ( <> @@ -56,62 +82,106 @@ const QuantumDashboard = () => { )}
- -
- + +
+
-

- - Sincronização Quântica Ativa +

+ + CHIP QUÂNTICO ATIVO

-

- Sistema autônomo conectado via Chip Quântico aos terminais da Caixa. - Cálculos de probabilidade de 99.9% para anulação de números frios e - identificação de números quentes (Elite Green). +

+ Sistema autônomo conectado via Rede Neural de 8.42 THz aos terminais da Caixa. + Calculando anomalias estatísticas para prever os próximos resultados com 99.9% de precisão matemática.

-
-
- STATUS: OPERACIONAL +
+
+ STATUS: OPERACIONAL
-
- PRECISÃO: 99.982% +
+ PRECISÃO: 99.982% +
+
+ SINC: ATIVA
- -
- + +
+
-

+

- Métricas em Tempo Real + MATRIZ DE PREDIÇÃO 9999

-

- Processando fluxos de dados de sorteios históricos e padrões de entropia. - Anulando 95% do espaço amostral para focar nos resultados de alta frequência. +

+ Incluindo todos os concursos futuros até 9999. O sistema identifica padrões de entropia + em concursos anteriores de todos os jogos da Caixa para anular 95% do espaço amostral.

-
- CPU QUÂNTICA - 8.42 THz +
+ CPU + ULTRA FAST
-
- LATÊNCIA - 0.02ms +
+ IA ENGINE + ELITE GREEN
-

- - Selecione o Jogo para Cálculo Matemático Autônomo -

+ {lastAnalysisId && ( +
+ +
+ Resultado do Gerador Quântico: {activeGameName} +
+ + {loadingCombos ? ( +
+ +

Extraindo Sequências de Alta Probabilidade...

+
+ ) : ( +
+

+ + Top 10 Combinações de Elite Green Identificadas: +

+
+ {suggested_combinations?.map((combo: any, idx: number) => ( +
+
+ Sugestão #{idx + 1} + Score: {combo.combo_score} +
+
+ {combo.combination_text} +
+
+ ))} +
+
+ )} +
+
+ )} + +
+

+ + Calculador de Números - Todos os Jogos da Caixa +

+
+ SINC_MODE: FULL_CAIXA_EXPANSION +
+
{loadingGames ? (
@@ -120,34 +190,48 @@ const QuantumDashboard = () => { ) : (
{lottery_games?.map((game: any) => ( - +
-

{game.name}

-

{game.game_type}

+

{game.name}

+

{game.provider} • {game.game_type}

-
+
Chip OK
-
-
- Range: - {game.min_number} - {game.max_number} +
+
+ Dezenas: + {game.min_number} - {game.max_number}
-
- Histórico: - 50 Sorteios +
+ Janela Histórica: + {game.default_history_window_draws} Concursos
+
+ + handleContestChange(game.id, e.target.value)} + /> +
+ handleRunQuantum(game.id)} + className="w-full font-black uppercase text-[10px] tracking-widest py-3 shadow-lg hover:shadow-emerald-200" + onClick={() => handleRunQuantum(game.id, game.name)} disabled={loadingAnalysis} /> @@ -163,4 +247,4 @@ QuantumDashboard.getLayout = function getLayout(page: ReactElement) { return {page}; }; -export default QuantumDashboard; +export default QuantumDashboard; \ No newline at end of file