[telegram] hay en /home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26
 unos documentos que hablan de las maquinas de tcn (chinos) para hacer vending de ballbox. quiero que los leas y primero los uses como nueva fuente de verdad para invalidar/retrabajar documentos viejos de la carpeta padre + sugerir cambios en la plataforma.
solo plan por ahora, sin cambios


**Planning memory inspection**

I need to inspect the documents, and I’m considering whether to use a to-do list for this. Maybe I should think about using memory, but I’m not sure if that’s necessary right now. My first plan involves reading the skill memory, although it might not be needed. Plus, I should create a to-do list for better organization and make sure to inspect the folder as well.

todo

Plan TCN machine docs review and platform impact

Review newly received TCN machine documents, compare against older parent-folder docs, identify invalidations/rework needed, and suggest platform changes. Plan only, no file changes yet.


Created #1: Plan TCN machine docs review and platform impact (pending)


bash

find /home/sebas/work/projects/ballbox/docs -maxdepth 2 -type d -name 'tcn-maquinas-recibido-2026-05-26' -o -path '/home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26' ; echo '---'; find /home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26 -maxdepth 2 -type f | sort ; echo '---PARENT---'; find /home/sebas/work/projects/ballbox/docs -maxdepth 1 -type f | sort


/home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26
---
/home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26/PARTE 1 - DOCUMENTACION MAESTRA DE INVESTIGACION Y OPERACION.docx
/home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26/PARTE 2 - Android USB Publicidad Exportaciones y Sistema Interno.docx
/home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26/PARTE 3 - EasyCoin BillWallet Operacion Comercial y Arquitectura Futura.docx
/home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26/PARTE 4 - Ingenieria Inversa Traducciones Backend Propio y Plan de Investigacion.docx
/home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26/PARTE 5 - Manual Operativo BallBox.docx
/home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26/PARTE 6 - Ingenieria Inversa Avanzada y Autonomia Tecnologica.docx
---PARENT---
/home/sebas/work/projects/ballbox/docs/atc-access-request-checklist.md
/home/sebas/work/projects/ballbox/docs/atc-integration-discovery.md
/home/sebas/work/projects/ballbox/docs/atc-integration-spec-skeleton.md
/home/sebas/work/projects/ballbox/docs/atc-mock-integration-plan.md
/home/sebas/work/projects/ballbox/docs/ballbox-db-plan.md
/home/sebas/work/projects/ballbox/docs/bb-002-slice-1-plan.md
/home/sebas/work/projects/ballbox/docs/classes-implementation-notes.md
/home/sebas/work/projects/ballbox/docs/classes-mvp-rfc.md
/home/sebas/work/projects/ballbox/docs/classes-subroute-plan.md
/home/sebas/work/projects/ballbox/docs/coach-availability-rfc.md
/home/sebas/work/projects/ballbox/docs/coaches-coordination-gap-analysis.md
/home/sebas/work/projects/ballbox/docs/coaches-design-partner-outreach.md
/home/sebas/work/projects/ballbox/docs/coaches-discovery-execution-plan.md
/home/sebas/work/projects/ballbox/docs/coaches-discovery-stage.md
/home/sebas/work/projects/ballbox/docs/coaches-form-current.md
/home/sebas/work/projects/ballbox/docs/coaches-icp-segmentation.md
/home/sebas/work/projects/ballbox/docs/coaches-interview-script.md
/home/sebas/work/projects/ballbox/docs/coaches-jtbd-workflow-map.md
/home/sebas/work/projects/ballbox/docs/coaches-opportunity-brief.md
/home/sebas/work/projects/ballbox/docs/coaches-research-repository.md
/home/sebas/work/projects/ballbox/docs/coaches-solution-thesis.md
/home/sebas/work/projects/ballbox/docs/coaches-validation-checklist-2-weeks.md
/home/sebas/work/projects/ballbox/docs/coaches-wedges-matrix.md
/home/sebas/work/projects/ballbox/docs/demo-iteration-mode.md
/home/sebas/work/projects/ballbox/docs/domain-model-target.md
/home/sebas/work/projects/ballbox/docs/html-first-accessibility-plan.md
/home/sebas/work/projects/ballbox/docs/implemented-host-app.md
/home/sebas/work/projects/ballbox/docs/implemented-network.md
/home/sebas/work/projects/ballbox/docs/implemented-payments.md
/home/sebas/work/projects/ballbox/docs/implemented-players.md
/home/sebas/work/projects/ballbox/docs/implemented-sports.md
/home/sebas/work/projects/ballbox/docs/implemented-tvs.md
/home/sebas/work/projects/ballbox/docs/index.md
/home/sebas/work/projects/ballbox/docs/maintainability-priorities-2026-03.md
/home/sebas/work/projects/ballbox/docs/mercadopago-webhook-replay-notes-2026-04-23.md
/home/sebas/work/projects/ballbox/docs/payments-club-settlement-strategy.md
/home/sebas/work/projects/ballbox/docs/payments-machine-implementation-rfc.md
/home/sebas/work/projects/ballbox/docs/payments-machine-rollout-rfc.md
/home/sebas/work/projects/ballbox/docs/repo-map.md
/home/sebas/work/projects/ballbox/docs/screen-runtime-delivery-investigation.md
/home/sebas/work/projects/ballbox/docs/streetcast-parity.md
/home/sebas/work/projects/ballbox/docs/tcn-payments-execution-plan.md
/home/sebas/work/projects/ballbox/docs/tcn-payments-integration-plan.md
/home/sebas/work/projects/ballbox/docs/tcn-payments-open-questions.md


EISDIR: illegal operation on a directory, read


**Considering document conversion**

I need to convert a DOCX file, so I'm thinking of unzipping it to get the XML or using textutil or LibreOffice. I'll inspect the relevant documents, perhaps looking at the TCN docs. My goal is to extract the text from the DOCX file. I might consider using Python with zip/xml functionality or even Pandoc. A bash loop could work for this process, so let’s explore the best approach!

python - <<'PY'
from zipfile import ZipFile
from pathlib import Path
import re
base=Path('/home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26')
for p in sorted(base.glob('*.docx')):
    print(f'===== {p.name} =====')
    with ZipFile(p) as z:
        data=z.read('word/document.xml').decode('utf-8','ignore')
    text=re.sub(r'<w:tab[^>]*/>', '\t', data)
    text=re.sub(r'</w:p>', '\n', text)
    text=re.sub(r'<[^>]+>', '', text)
    text=text.replace('&','&').replace('<','<').replace('>','>')
    lines=[ln.strip() for ln in text.splitlines()]
    lines=[ln for ln in lines if ln]
    for ln in lines[:120]:
        print(ln)
    if len(lines)>120:
        print(f'...[{len(lines)-120} more lines]')
    print()
PY

for f in /home/sebas/work/projects/ballbox/docs/tcn-payments-*.md /home/sebas/work/projects/ballbox/docs/payments-machine-*.md /home/sebas/work/projects/ballbox/docs/implemented-payments.md /home/sebas/work/projects/ballbox/docs/screen-runtime-delivery-investigation.md; do echo "===== $(basename "$f") ====="; sed -n '1,220p' "$f"; echo; done


===== PARTE 1 - DOCUMENTACION MAESTRA DE INVESTIGACION Y OPERACION.docx =====
BALLBOX
DOCUMENTACIÓN MAESTRA DE INVESTIGACIÓN Y OPERACIÓN
Máquinas Expendedoras TCN / OurVend
Versión 1.0 (Bitácora completa)
PROPÓSITO DEL DOCUMENTO
Este documento existe para evitar perder conocimiento.
La idea NO es generar un resumen ejecutivo.
La idea es que cualquier integrante de BallBox pueda tomar este documento dentro de seis meses o dos años y continuar exactamente desde el punto donde quedó la investigación.
Por ese motivo se documentan:
Hallazgos confirmados.
Errores encontrados.
Pruebas realizadas.
Hipótesis.
Configuraciones.
Procedimientos.
Dudas pendientes.
Decisiones tomadas.
Incluso si una hipótesis resulta incorrecta, se documenta porque evita repetir experimentos.
ESTADO DEL PROYECTO AL MOMENTO DE ESCRIBIR ESTE DOCUMENTO
La investigación comenzó sobre máquinas expendedoras TCN provenientes de China.
Objetivos iniciales:
Comprender funcionamiento interno.
Comprender configuración de software.
Conectar internet.
Configurar productos.
Configurar imágenes.
Configurar publicidad.
Configurar idiomas.
Integrar medios de pago.
Evaluar independencia futura respecto de OurVend.
Al comenzar la investigación prácticamente no existía conocimiento operativo sobre la plataforma.
Actualmente:
CONFIRMADO:
Conexión WiFi.
Acceso Android.
Acceso backstage.
Configuración de slots.
Prueba de motores.
Prueba de expulsión.
Conexión OurVend.
Modificación remota de stock.
Modificación remota de precios.
Importación USB.
Publicidad por imágenes.
Publicidad por video.
Exportación de configuración.
Exportación de logs.
Exportación de base SQLite.
Integración EasyCoin.
Integración BillWallet.
Cobro real con liberación de producto.
PENDIENTE:
Traducción completa.
Comprensión completa de ImageGoods.
Comprensión completa de Text.
Comprensión completa de v3Skins.
Publicidad remota online.
Comprensión protocolo TCP.
Posible backend propio.
IDENTIFICACIÓN DE LA MÁQUINA
Modelo observado:
TCN-CSC-8C(V49)
Machine ID observado:
2601070188
Resolución:
1920x1080
Orientación:
Vertical
Main Board:
TCN-STANDJS
Puerto serie principal:
/dev/ttyS2
Baud rate:
9600
Servidor configurado:
qrc.ourvend.com
Puerto configurado:
4150
Aplicación Android observada:
TCN-SD-05-V1.0.0.13-20251210.01
Android:
Rockchip K518 Android 7.1.2
Memoria observada:
1.95 GB RAM
Almacenamiento:
7.28 GB
ARQUITECTURA GENERAL DETECTADA
Luego de múltiples pruebas se concluye que la arquitectura parece dividirse en tres componentes:
OurVend
Responsable de:
nube
stock
precios
sincronización
monitoreo
Android
Responsable de:
interfaz gráfica
publicidad
multimedia
idioma
sincronización con servidor
Main Board
Responsable de:
motores
sensores
bandejas
dispensado
Esquema simplificado:
OurVend Cloud
↓
Android TCN
↓
Main Board
↓
Motores
↓
Producto
INVESTIGACIÓN DE RED
Primer problema encontrado
...[111 more lines]

===== PARTE 2 - Android USB Publicidad Exportaciones y Sistema Interno.docx =====
BALLBOX
DOCUMENTACIÓN MAESTRA DE INVESTIGACIÓN Y OPERACIÓN
PARTE 2
Android, USB, Publicidad, Exportaciones y Sistema Interno
INVESTIGACIÓN DEL SISTEMA ANDROID
Uno de los descubrimientos más importantes fue comprobar que la máquina no es simplemente una vending tradicional.
La máquina contiene una computadora Android completa.
Esto cambia completamente el enfoque de la investigación.
Inicialmente se pensaba que la máquina era:
Pantalla+Controladora+Motores
Sin embargo se comprobó que existe:
Android
con:
almacenamiento interno
sistema operativo
aplicaciones
configuración propia
explorador de archivos
sistema de actualización
ACCESO AL SISTEMA
Se logró acceder a:
Android Settings
Configuración estándar Android.
Desde allí es posible:
revisar WiFi
revisar almacenamiento
revisar aplicaciones
revisar configuración del sistema
ES Browser
Se confirmó existencia de explorador de archivos.
Esto permite navegar:
memoria interna
carpetas exportadas
archivos de publicidad
Menú técnico
También denominado backstage.
Permite:
configuración de máquina
configuración de motores
configuración de slots
publicidad
exportaciones
diagnóstico
ADVERTENCIA IMPORTANTE
Se encontró pantalla con advertencia:
Please do not change the parameters here, or the machine will not work properly.
Conclusión:
No modificar parámetros desconocidos.
Especialmente:
seriales
puertos
board type
configuraciones de servidor
sin respaldo previo.
INVESTIGACIÓN DEL USB
Uno de los objetivos era determinar:
dónde conectar el USB
cómo importar contenido
cómo exportar configuraciones
PROBLEMA INICIAL
Existían múltiples puertos USB.
No estaba claro cuál utilizaba la máquina.
Se observaron:
USB superior
USB inferior
DESCUBRIMIENTO
El puerto funcional para importaciones resultó ser:
USB inferior
FORMATO DEL PENDRIVE
Recomendado:
FAT32
En Mac:
MS-DOS (FAT)
ESTRUCTURA NECESARIA
La máquina espera:
TCNFolder
en la raíz.
No es necesario renombrar el pendrive.
Debe existir:
TCNFolder/
PRIMERA IMPORTACIÓN EXITOSA
Al conectar el USB apareció mensaje en chino.
Texto observado:
是否拷贝TcnFolder文件夹内容？
Traducción aproximada:
¿Desea copiar el contenido de TcnFolder?
Botones:
Cancelar
Copiar
Se eligió:
Copiar
RESULTADO
No apareció mensaje de éxito.
Sin embargo:
después del reinicio
el contenido visual cambió.
Conclusión:
la importación fue exitosa.
COMPORTAMIENTO DETECTADO
La máquina NO utiliza el USB permanentemente.
Realiza:
USB
↓
Copiar
↓
Memoria interna Android
↓
Funcionamiento normal
DESCUBRIMIENTO CRÍTICO
Apareció carpeta:
sdcard/TcnFolder
Esto confirma:
los recursos son almacenados localmente.
IMPLICANCIA
Posiblemente sea viable en el futuro:
descargar contenido vía internet
y escribir directamente en:
sdcard/TcnFolder
sin utilizar pendrive.
PUBLICIDAD
...[206 more lines]

===== PARTE 3 - EasyCoin BillWallet Operacion Comercial y Arquitectura Futura.docx =====
BALLBOX
DOCUMENTACIÓN MAESTRA DE INVESTIGACIÓN Y OPERACIÓN
PARTE 3
EasyCoin, BillWallet, Operación Comercial y Arquitectura Futura
INTRODUCCIÓN
Una vez validado el funcionamiento mecánico y la conectividad de la máquina, el siguiente objetivo fue validar el flujo real de cobro.
La empresa utilizada para pagos es:
EasyCoin
La gestión de dispositivos y cuentas se realiza mediante:
BillWallet
INSTALACIÓN DEL DISPOSITIVO EASYCOIN
Se recibió un dispositivo EasyCoin.
La instalación fue realizada junto con personal de la empresa.
Resultado:
Instalación exitosa.
PRUEBA DE COBRO
Se realizaron pruebas reales.
Resultado observado:
Usuario selecciona producto.
Usuario realiza pago.
EasyCoin recibe confirmación.
Máquina libera el canal.
Producto cae correctamente.
Estado:
CONFIRMADO.
OBSERVACIÓN SOBRE EL BALANCE
Durante las pruebas apareció un valor de balance en pantalla.
Sin embargo:
No se observó modificación visible del balance cuando ingresó dinero.
A pesar de ello:
La máquina liberó correctamente el producto.
Hipótesis:
El balance visible pertenece al firmware TCN y no al flujo principal de EasyCoin.
Pendiente:
Confirmar con EasyCoin.
BILLWALLET
BillWallet es la plataforma de administración utilizada por EasyCoin.
Cada dispositivo queda asociado a una cuenta BillWallet.
Importante:
La asociación se realiza con el usuario.
NO con el dispositivo.
RELACIÓN ENTRE DISPOSITIVOS Y MERCADOPAGO
Arquitectura observada:
Dispositivo
↓
Usuario BillWallet
↓
MercadoPago
Consecuencia:
Un usuario puede administrar múltiples dispositivos.
Todos los dispositivos cobran al mismo MercadoPago.
EJEMPLO BALLBOX
Cuenta BallBox
↓
Máquina Club A
Máquina Club B
Máquina Club C
Máquina Club D
↓
Todos los pagos llegan a la misma cuenta MercadoPago.
VENTAJAS DEL MODELO CENTRALIZADO
BallBox recibe toda la recaudación.
Ventajas:
Control total de ventas.
Control total de stock.
Conciliación simplificada.
Pago mensual a clubes.
Menor riesgo de diferencias de inventario.
Posibilidad de aprovechar flujo de caja.
DESVENTAJAS DEL MODELO CENTRALIZADO
Mayor responsabilidad administrativa.
Mayor responsabilidad financiera.
Necesidad de conciliación periódica.
Posibles cuestiones impositivas futuras.
MODELO DESCENTRALIZADO
Alternativa:
Cada club crea su propio usuario BillWallet.
Cada club conecta su propio MercadoPago.
Resultado:
Los fondos llegan directamente al club.
VENTAJAS
BallBox no administra dinero ajeno.
Menor responsabilidad financiera.
DESVENTAJAS
Menor control.
Menor visibilidad.
Más difícil verificar ventas.
Posibilidad de discrepancias de stock.
USUARIOS ADICIONALES
BillWallet permite agregar usuarios.
Posible implementación:
Club:
Administrador Club
BallBox:
Administrador BallBox
Objetivo:
Acceder a métricas y monitoreo.
Pendiente:
Validar si un administrador puede eliminar a otro usuario.
QR DE PAGO
Cada cuenta BillWallet genera un QR.
Proceso observado:
Configurar MercadoPago.
Generar QR.
Descargar QR.
Imprimir QR.
Colocar QR en la máquina.
OBSERVACIÓN IMPORTANTE
Si cambia el MercadoPago:
El QR cambia.
Por lo tanto:
Debe reemplazarse el QR físico.
REGLA OPERATIVA
Siempre verificar:
□ QR actualizado
□ MercadoPago correcto
□ Impresión correcta
□ QR visible para usuarios
API EASYCOIN
Descubrimiento muy importante.
...[115 more lines]

===== PARTE 4 - Ingenieria Inversa Traducciones Backend Propio y Plan de Investigacion.docx =====
BALLBOX
DOCUMENTACIÓN MAESTRA DE INVESTIGACIÓN Y OPERACIÓN
PARTE 4
Ingeniería Inversa, Traducciones, Backend Propio y Plan de Investigación
INTRODUCCIÓN
Al momento de redactar esta sección, la máquina ya es operativa.
Se validó:
WiFi
Android
Publicidad local
OurVend
EasyCoin
BillWallet
Exportaciones
Logs
SQLite
La pregunta ya no es:
¿Cómo usar la máquina?
La pregunta pasa a ser:
¿Cómo funciona internamente?
y
¿Cuánto control puede obtener BallBox sin depender de terceros?
OBJETIVO ESTRATÉGICO
Idealmente BallBox debería controlar:
experiencia visual
publicidad
catálogo
métricas
inventario
pagos
promociones
usuarios
independientemente de OurVend.
SISTEMA DE TRADUCCIONES
Situación actual
La interfaz aparece parcialmente:
en español
en inglés
en chino
simultáneamente.
Evidencias
En TrayPreferences aparecen:
yuyan = en
WmLanguage = español
new_background_language = English
is_use_language_package = true
Conclusión
La aplicación soporta múltiples mecanismos de idioma.
No parece existir una única configuración global.
Hipótesis
Posiblemente existan:
Traducciones embebidas
Dentro del APK.
Traducciones externas
En:
Text
Traducciones de skins
En:
v3Skins
Traducciones descargadas
Desde servidor.
PLAN DE INVESTIGACIÓN DE IDIOMAS
Paso 1
Analizar:
Text
Paso 2
Analizar:
v3Skins
Paso 3
Buscar:
json
xml
properties
lang
language
Paso 4
Localizar popup chino observado durante importación USB.
Objetivo final
Máquina completamente en español.
IMAGEGOODS
Situación actual
La carpeta existe.
No se conoce función exacta.
Hipótesis principal
Contiene imágenes de productos.
Motivo
Nombre:
ImageGoods
↓
Imagenes de productos
Experimento recomendado
Agregar:
Wilson.jpg
Bullpadel.jpg
Nox.jpg
Importar nuevamente.
Verificar:
catálogo
selección
carrito
vista previa
V3SKINS
Situación actual
Detectada.
No investigada.
Hipótesis
Contiene:
temas
branding
logos
layouts
colores
Importancia
Muy alta.
Si se confirma:
BallBox podría reemplazar branding chino.
PUBLICIDAD REMOTA
Hallazgos
TrayPreferences contiene:
AdvertRemote = false
...[167 more lines]

===== PARTE 5 - Manual Operativo BallBox.docx =====
BALLBOX
DOCUMENTACIÓN MAESTRA DE INVESTIGACIÓN Y OPERACIÓN
PARTE 5
Manual Operativo BallBox
RECEPCIÓN DE UNA MÁQUINA NUEVA
Cuando llega una máquina desde China:
NO asumir que viene lista para operar.
Debe pasar por preparación interna.
Checklist de recepción
Verificar:
□ golpes externos
□ vidrio intacto
□ puerta cierra correctamente
□ cerradura funcional
□ llaves presentes
□ cable alimentación presente
□ antena presente
□ bandejas presentes
□ espirales presentes
□ pantalla en buen estado
□ lector EasyCoin presente (si corresponde)
PRIMER ENCENDIDO
Conectar energía.
Encender máquina.
Esperar arranque completo.
Validar
□ pantalla enciende
□ Android inicia
□ interfaz principal aparece
□ no hay errores visibles
CONEXIÓN A INTERNET
Ingresar a configuración.
Buscar WiFi.
Si no aparecen redes
Probar:
Hotspot iPhone
↓
Maximizar compatibilidad
↓
buscar nuevamente
Si aparece
Conectar.
Esperar sincronización.
VALIDACIÓN DE CLOUD
Ingresar a OurVend.
Verificar:
□ máquina visible
□ comunicación activa
□ stock sincronizado
□ precios sincronizados
VALIDACIÓN DE MOTORES
Ingresar:
Slot Management
Probar:
todos los canales
sin excepción
Validar
□ gira
□ no traba
□ no hace ruido extraño
□ completa recorrido
PRUEBA DE CAÍDA
Colocar producto.
Ejecutar venta de prueba.
Confirmar:
□ producto cae
□ no queda colgado
□ siguiente producto permanece estable
CONFIGURACIÓN DE BANDEJAS
Ajustar altura.
Ajustar separación.
Ajustar canales.
TUBOS DE PELOTAS
Regla BallBox:
NO dejar libres.
Configurar:
canal doble
apoyado lateralmente
Validar:
múltiples ventas consecutivas
MEDIAS Y TEXTILES
Evitar:
paso debajo del espiral
Validar:
caída real
CARGA DE PRECIOS
Desde cloud.
Validar:
precio correcto
visible correctamente
CARGA DE STOCK
Desde cloud.
Validar:
cantidad correcta
CONFIGURACIÓN DE PUBLICIDAD
Ir:
Basic Setting
Ads Setting
Configurar:
Idle Ads Display = ON
Standby Full Screen = ON
Idle Time = 60
Ads Bottom = ON
IMPORTACIÓN DE PUBLICIDAD
Preparar USB FAT32.
Crear:
TCNFolder
Copiar contenido.
Conectar USB inferior.
Ejecutar:
Import Ads
Aceptar.
Reiniciar.
Validar:
imágenes
videos
EASYCOIN
Verificar:
□ dispositivo conectado
□ alimentación correcta
...[87 more lines]

===== PARTE 6 - Ingenieria Inversa Avanzada y Autonomia Tecnologica.docx =====
BALLBOX
DOCUMENTACIÓN MAESTRA DE INVESTIGACIÓN Y OPERACIÓN
PARTE 6
Ingeniería Inversa Avanzada y Autonomía Tecnológica
INTRODUCCIÓN
Hasta este punto la máquina funciona.
Sin embargo BallBox depende todavía de varios terceros:
TCN
OurVend
EasyCoin
BillWallet
La pregunta estratégica pasa a ser:
¿Qué dependencias podemos eliminar?
DEPENDENCIAS ACTUALES
Hardware
TCN
Actualmente inevitable.
Cloud
OurVend
Actualmente obligatorio.
Pagos
EasyCoin
Actualmente necesario.
Cobro
MercadoPago
Actualmente necesario.
OBJETIVO FINAL
Arquitectura deseada:
Usuario
↓
ATC
↓
Backend BallBox
↓
Máquina
Sin depender operativamente de:
OurVend
INVESTIGACIÓN DE PROTOCOLO
Hallazgo
En logs aparece:
qrc.ourvend.com
puerto 4150
Además aparecen:
TCPClient
socket connect
heartbeat
mensajes JSON
Conclusión
La máquina habla TCP.
PREGUNTAS ABIERTAS
¿Cómo autentica?
¿Cómo registra máquina?
¿Cómo sincroniza slots?
¿Cómo sincroniza stock?
¿Cómo sincroniza precios?
¿Cómo descarga publicidad?
CAPTURA DE TRÁFICO
Herramienta recomendada:
Wireshark
Procedimiento
Conectar máquina a red controlada.
Capturar tráfico.
Filtrar:
4150
Objetivos
Identificar:
JSON
endpoints
autenticación
comandos
FTP DETECTADO
Encontrado:
ad.ourvend.com
Usuario:
ysftp
Contraseña exportada.
Preguntas
¿FTP sigue activo?
¿Se puede conectar?
¿Qué directorios existen?
¿Hay carpetas por Machine ID?
¿Hay publicidad?
¿Hay idiomas?
¿Hay skins?
EXPERIMENTO FTP
Realizar desde PC.
Intentar conexión.
Objetivo:
listar contenido.
NO modificar nada.
Sólo lectura.
ACTUALIZACIONES OTA
Encontrado:
update.xml
Servidor:
tfs.android.tcnvmms.com
Preguntas
¿Qué actualiza?
APK
Recursos
Idiomas
Configuraciones
Objetivo
Descargar update.xml.
Analizar.
SISTEMA DE IDIOMAS
Hallazgo:
is_use_language_package=true
Conclusión:
Existe soporte para paquetes externos.
Objetivo
Encontrar:
language package
Posibles ubicaciones:
Text
v3Skins
Android/data
META
Traducción completa BallBox.
V3SKINS
...[127 more lines]


===== tcn-payments-execution-plan.md =====
# TCN payments execution plan

## Purpose
Ordered execution plan for getting from current Ballbox native Mercado Pago support to real TCN machine payments.

## Step 1. Finish provider-layer proof
- Goal: prove Ballbox native Mercado Pago flow works end to end without TCN hardware.
- Inputs:
  - `docs/implemented-payments.md`
  - `docs/mercadopago-webhook-replay-notes-2026-04-23.md`
- Tasks:
  - validate public webhook reachability for `/notification/mercadopago`
  - run one real approved payment
  - confirm local `PaymentSession` persistence in `/admin/payments`
  - document exact payload and public URL evidence
- Exit criterion:
  - one real approved payment persists locally through webhook flow

## Step 2. Ask TCN the machine-contract questions
- Goal: close the remaining machine-side unknowns before coding the adapter.
- Inputs:
  - `docs/tcn-payments-integration-plan.md`
  - `docs/tcn-payments-open-questions.md`
  - `test-results/tcn-payment-protocol/findings-2026-04-23.md`
- Tasks:
  - send the question list to the TCN sales contact
  - ask them to confirm with engineers
  - capture answers in repo docs
- Exit criterion:
  - `CodeUrl` meaning and payment-success handshake are confirmed

## Step 3. Freeze Ballbox-TCN contract
- Goal: convert answers into a concrete adapter spec.
- Inputs:
  - `docs/tcn-payments-integration-plan.md`
  - answers captured from Step 2
- Tasks:
  - define request/response schema for TCN `8000`
  - define success/failure callback or polling behavior
  - define duplicate/idempotency behavior for repeated `TradeNo`
  - define machine-id mapping rules
- Exit criterion:
  - implementation spec is precise enough to code without guesswork

## Step 4. Implement adapter layer
- Goal: add the TCN-facing Ballbox endpoints over existing Mercado Pago primitives.
- Inputs:
  - concrete contract spec from Step 3
- Tasks:
  - add machine-facing endpoint(s)
  - map TCN requests to Ballbox/Mercado Pago order creation
  - map approved-payment state back into TCN success flow
  - persist any extra machine correlation fields needed
- Exit criterion:
  - local/manual adapter flow works without real machine hardware

## Step 5. Hardware validation when machines arrive
- Goal: verify actual stock TCN machine behavior.
- Tasks:
  - test real QR render on machine screen
  - test payment approval -> vend path
  - capture timing, retries, and failure cases
- Exit criterion:
  - one real vend succeeds through Ballbox-backed payment flow

## Step 6. Only then revisit payout automation
- Goal: avoid solving club payout distribution before the machine path is stable.
- Current default:
  - scheduled manual settlements / bookkeeping
- Related docs:
  - `docs/payments-club-settlement-strategy.md`

===== tcn-payments-integration-plan.md =====
# TCN payments integration plan

## Decision
- Treat the current `/admin/payments` QR generator as an operator test harness, not the final production payment UX for vending machines.
- Production vending flow should integrate with the TCN machine protocol and let the machine render the buyer-facing QR on its own screen.

## Why
- TCN protocol `2.5V` states: `to scan QR codes additional hardware devices are necessary.`
- That wording applies to **machine-side QR scanning**, not to the machine displaying a QR on its screen for the buyer to scan with a phone.
- The payment section (`2.1.5 Integral exchange`, `FunCode=8000`) already defines a dynamic payment flow:
  - machine sends `MachineID`, `TradeNo`, `SlotNo`, `Price`, `NotityUrl`
  - server returns `CodeUrl`, `TradeNo`
- `CodeUrl` is described as the returned value used to generate the QR code.
- That is enough to proceed with integration planning without assuming extra scanner hardware.

## Intended production flow
1. Buyer selects product on TCN machine.
2. TCN machine requests Ballbox payment session using the TCN payment contract.
3. Ballbox creates a Mercado Pago QR order.
4. Ballbox maps the Mercado Pago output into the TCN response shape and returns `CodeUrl`.
5. TCN machine renders the QR on its screen.
6. Buyer scans with Mercado Pago app on phone.
7. Payment provider notifies Ballbox webhook.
8. Ballbox validates/persists approved payment.
9. TCN machine receives the success signal through the TCN-side notify/result path and dispenses product.

## Ballbox work now
### 1. Lock the machine-facing contract
- Define a Ballbox route for TCN `8000` payment-init requests.
- Define exact request/response mapping for:
  - `MachineID` -> Ballbox `vendingMachineId` or external machine identifier
  - `TradeNo` -> machine transaction id / canonical `externalReference`
  - `SlotNo`
  - `Price`
  - `NotityUrl`
  - response `CodeUrl`
- Confirm whether TCN expects raw payment URL, QR payload string, or a specific provider deep link in `CodeUrl`.

### 2. Define result/dispense handshake
- Map how Ballbox should signal payment success back into the TCN flow.
- Verify whether Ballbox must call `NotityUrl`, expose a callback endpoint, or rely on a polling/result interface in the broader TCN protocol set.
- Confirm how TCN links approved payment to dispense using `TradeNo` and/or `SlotNo`.

### 3. Normalize machine identity
- Decide the canonical mapping between TCN `MachineID` and Ballbox `VendingMachine`.
- Add any missing external-id field only if needed for clean lookup.

### 4. Keep admin QR page as a test tool
- `/admin/payments` remains useful for:
  - Mercado Pago config checks
  - live QR creation smoke tests
  - webhook validation
  - manual provider debugging
- Do not frame it as the final vending-machine payment UX.

## Unknowns still to close
- Exact payload expected inside TCN `CodeUrl`.
- Exact success callback / notify shape between Ballbox and TCN after payment approval.
- Whether machine-side polling (`4000`) participates in payment completion or only app-driven vend/load flows.
- Whether TCN needs additional payment-status endpoints beyond `8000` for a full dispense flow.

## Recommendation
- Next implementation slice should be a TCN adapter spec + stub endpoints, not more work on the standalone admin QR page.
- Keep Mercado Pago-native Ballbox routes as the provider layer underneath that adapter.

## Evidence
- `test-results/tcn-payment-protocol/Protocol 2.5V English version.pdf`
- `test-results/tcn-payment-protocol/findings-2026-04-23.md`

===== tcn-payments-open-questions.md =====
# TCN payments open questions

## Goal
Close the remaining machine-integration unknowns before Ballbox implements the full TCN adapter.

## Questions for TCN sales / engineering
1. In `FunCode=8000`, what exact value should Ballbox return in `CodeUrl`?
   - raw URL
   - QR payload string
   - Mercado Pago deep link
   - other provider-specific format
2. After payment approval, how does the machine learn that the vend can proceed?
   - Ballbox calls the request `NotityUrl`
   - machine polls another TCN endpoint
   - cloud pushes through `4000`
   - other flow
3. Is `NotityUrl` always machine-provided per transaction, or is there also a machine-level configured callback?
4. What is the exact payload shape expected for the payment-success notify/result message?
5. Which field is the true dispense correlation key?
   - `TradeNo`
   - `SlotNo`
   - both
   - another internal machine field
6. Does the stock TCN app render the QR natively after a successful `8000` response, or is any machine-side UI configuration required?
7. Are there any timeout / expiry expectations for the QR payment window from the machine side?
8. What should Ballbox return to the machine when payment creation fails or times out?
9. Is there any machine retry behavior Ballbox must tolerate for duplicate `TradeNo` requests?
10. Are there additional payment-related endpoints beyond `8000` required for a production dispense flow?

## Questions for Mercado Pago / internal validation
1. Which returned value from Ballbox should be safest to map into TCN `CodeUrl` for dynamic QR display?
2. Does current Ballbox order creation produce the same QR/deeplink payload shape expected by a buyer using Mercado Pago app?
3. Is the current webhook exposure stable enough for real public notifications on the production-like Ballbox URL?
4. Are there provider-side expiry, duplicate-order, or idempotency constraints we should encode before machine rollout?

## Output expected from this doc
- A resolved field-mapping note added back into `docs/tcn-payments-integration-plan.md`
- A concrete implementation spec once answers arrive

===== payments-machine-implementation-rfc.md =====
# Payments machine implementation RFC

## Status
- Proposed technical implementation slice for `PAY-3`.
- Builds on `docs/payments-machine-rollout-rfc.md`.

## Goal
Implement one machine-payment flow in Ballbox that:
- serves TCN machines
- creates Mercado Pago QR orders
- persists approved payments through the Ballbox webhook
- supports two payment-owner modes without forking the stack:
  - `BALLBOX`
  - `TENANT`

## Non-goals
- full split settlement automation
- tenant self-serve onboarding
- final long-term tenant account admin UX
- production-grade accounting ledger in this slice

## Current code baseline
Existing implemented pieces:
- order create route: `app/api/integrations/payments/orders/route.ts`
- webhook intake: `app/notification/mercadopago/route.ts`
- provider helper: `lib/payments-mercadopago.ts`
- payment persistence + correlation: `lib/payments.ts`
- payment contracts: `lib/contracts/payments.ts`

Current limitation:
- provider config is effectively global via Ballbox env (`BALLBOX_MERCADOPAGO_*`)
- webhook fetch path currently assumes one Mercado Pago config
- machine-facing TCN adapter does not exist yet

## Proposed architecture

### 1. Separate provider config resolution from raw env access
Create a resolver layer that answers:
- which payment-owner mode applies to this machine/request/order
- which Mercado Pago config should be used

Proposed concept:
- `lib/payments-mercadopago-config.ts`

Responsibilities:
- resolve `BALLBOX` default config from env
- resolve `TENANT` config from a Ballbox-owned machine/tenant mapping source
- return a normalized config object used by both order-create and webhook-fetch flows

Suggested shape:
```ts
export type PaymentOwnerMode = "BALLBOX" | "TENANT";

export type MercadoPagoConfigResolved = {
  ownerMode: PaymentOwnerMode;
  ownerKey: string; // e.g. ballbox-default or tenant/adidas-001
  accessToken: string;
  webhookSecret: string | null;
  externalPosId: string | null;
  publicApiBaseUrl: string;
};
```

## 2. Resolve payment owner per machine
Ballbox needs a deterministic way to know which owner mode applies before creating an order.

Short-term recommendation:
- add machine-level payment ownership fields to the Ballbox data model
- keep it simple and explicit, not inferred from club type or naming

Suggested fields at machine level:
- `paymentOwnerMode`
- `paymentOwnerKey`
- optional override `paymentExternalPosId`

Meaning:
- `paymentOwnerMode`: `BALLBOX` or `TENANT`
- `paymentOwnerKey`: resolver key for the MP config to use
- `paymentExternalPosId`: optional machine-specific override when not using the owner default POS

If schema change should stay smaller in step 1, fallback is:
- temporary in-code or env-backed mapping by `vendingMachineId`
- but only as a bridge; repo docs should still target DB-backed ownership

## 3. Preserve owner resolution in the order correlation path
Webhook processing must re-discover the correct MP credentials later.

Today Ballbox correlation key is:
- `payment-vm_{vendingMachineId}-txn_{machineTxnId}`

Keep that canonical reference.
But add enough persistence so webhook-triggered fetch can derive config without guessing.

Recommended minimum persisted fields on payment/session side:
- `vendingMachineId`
- canonical `externalReference`
- provider order id
- `paymentOwnerMode`
- `paymentOwnerKey`

If `PaymentSession` should remain approved-only and lean, add a lightweight pre-approval payment operation record instead.

## 4. Introduce a pre-approval payment operation record
Reason:
- webhook can arrive before a final approved `PaymentSession` exists
- Ballbox needs a stable place to remember which config created which provider order

Recommendation:
- add a lightweight table for initiated machine payments

Suggested record name:
- `PaymentOperation`

Suggested fields:
- `id`
- `vendingMachineId`
- `machineTxnId`
- `externalReference`
- `provider` (`MERCADOPAGO`)
- `providerOrderId`
- `paymentOwnerMode`
- `paymentOwnerKey`
- `externalPosId`
- `amountMinor`
- `status` (`CREATED`, `APPROVED`, `FAILED`, `EXPIRED`)
- `tenantLabel` or `notes` optional
- timestamps

Why this helps:
- webhook can resolve order id -> `PaymentOperation` -> correct MP config
- Ballbox can detect duplicate machine requests by `externalReference`
- later vend/result handling has a more natural source row than only approved sessions

## 5. Refactor provider helpers to accept explicit config
Current helpers mostly read env internally.
That blocks multi-owner support.

Refactor target:
- `fetchMercadoPagoOrder(orderId, config)`
- `createMercadoPagoQrOrder(input, config)`
- `getMercadoPagoConfig()` becomes only the `BALLBOX` default resolver or disappears behind the resolver module

Rule:
- business flows decide config first
- provider helpers never decide owner mode themselves

## 6. Add a machine-facing service layer before routes
Suggested module:
- `lib/payments-machine-flow.ts`

Responsibilities:
- resolve machine owner mode/config
- build canonical external reference
- create or reuse payment operation row
- call Mercado Pago order create
- return Ballbox-normalized result for either admin or TCN routes

Suggested main functions:
```ts
createMachinePaymentSession({
  vendingMachineId,
  machineTxnId,
  amountMinor,
  productId,
  source, // admin | tcn
})

resolvePaymentOwnerForMachine(vendingMachineId)

recordWebhookApproval({ orderId, externalReference, ... })
```

## 7. TCN route should sit on top of the machine-payment service
Recommendation:
- do not embed MP logic directly in TCN route handlers
- TCN route should translate between TCN contract and Ballbox machine-payment service only

Proposed route family:
- `app/api/integrations/tcn/payments/init/route.ts` or similar

That route should:
- parse TCN request
- resolve machine + amount + trade number
- call machine-payment service
- return TCN response shape including `CodeUrl`

## 8. Keep admin QR route as test harness over the same service
Admin route should reuse the same service layer where possible.
That avoids a separate payment stack for admin testing vs machine runtime.

Result:
- `/api/integrations/payments/orders` becomes a Ballbox test/operator entrypoint
- TCN adapter becomes the real machine entrypoint
- both converge on one machine-payment service underneath

## Data model recommendation

### Preferred
Add machine ownership to `VendingMachine` and payment initiation state to a new `PaymentOperation` table.

### Why preferred
- machine-level owner mode is operational truth
- webhook correlation becomes reliable
- future reporting becomes easier
- tenant setup does not need route-local hacks or env naming tricks

### Minimum viable fallback if schema must wait
- machine owner config stored in a local mapping module keyed by `vendingMachineId`
- provider order id + owner key persisted in a file/temporary table substitute

This fallback is weaker and should be temporary only.

## Webhook resolution strategy

### Preferred path
1. webhook payload yields `orderId`
2. Ballbox tries to find `PaymentOperation` by `providerOrderId`
3. from that row Ballbox gets `paymentOwnerMode` + `paymentOwnerKey`
4. Ballbox resolves MP config
5. Ballbox fetches order from MP

===== payments-machine-rollout-rfc.md =====
# Payments + machine rollout RFC

## Status
- Proposed operating plan for the first vending rollout.
- Use this as the master document for payment ownership modes, TCN integration, onboarding, and rollout sequencing.

## Decision summary
- Use one Ballbox-controlled technical flow for all vending machines.
- Support two payment-owner modes in that flow:
  - `BALLBOX`: Ballbox owns the Mercado Pago account that collects funds.
  - `TENANT`: the client/tenant owns the Mercado Pago account that collects funds.
- Default first rollout:
  - 3 club machines use `BALLBOX` collection.
  - 2 Adidas rental machines use `TENANT` collection.
- For `BALLBOX` collection, club revenue share is handled by informal/manual settlement at first.
- Do not block rollout on Mercado Pago native split or marketplace approval.
- Keep future split automation as an optional later track, not a prerequisite.

## Why this is the right first plan
- The immediate risk is not payout automation. The immediate risk is getting the machine payment path working end to end.
- TCN machine integration and Mercado Pago webhook persistence are still the highest-risk technical pieces.
- The first wave is small: 5 machines total.
- Manual settlement is acceptable for the 3 Ballbox-collected club machines.
- Adidas-style rental machines need easy setup more than Ballbox ownership of the funds.
- Running all machines through Ballbox keeps one integration surface, one webhook surface, and one observability path.

## Scope
### In scope
- TCN machine payment adapter
- Mercado Pago provider integration through Ballbox
- machine-level payment-owner mode selection
- Ballbox-collected club machines
- tenant-collected Adidas/client machines
- webhook handling through Ballbox
- manual settlement guidance for Ballbox-collected club machines
- onboarding steps that include non-code work

### Out of scope for this phase
- Mercado Pago marketplace/split as a requirement for launch
- fully automated club settlements
- self-serve onboarding for tenants/clubs
- long-term tenant MP support beyond guided setup

## Operating modes

### Mode A: `BALLBOX`
Use for the first 3 club machines.

Flow:
1. machine belongs to a club/venue
2. Ballbox creates the Mercado Pago order with Ballbox credentials
3. buyer pays by scanning the QR shown by the machine
4. Mercado Pago notifies Ballbox webhook
5. Ballbox fetches order details, verifies approval, persists payment
6. Ballbox later settles the club share manually

Properties:
- simplest first rollout
- Ballbox controls setup and debugging
- informal manual settlement is enough at this stage

### Mode B: `TENANT`
Use for the first 2 Adidas rental machines.

Flow:
1. machine belongs to a client/tenant contract
2. Ballbox creates the Mercado Pago order using tenant credentials/config
3. buyer pays by scanning the QR shown by the machine
4. Mercado Pago notifies the same Ballbox webhook endpoint
5. Ballbox fetches order details with the tenant-specific credentials, verifies approval, persists payment
6. tenant owns funds; Ballbox is not doing revenue-share settlement for those payments

Properties:
- Ballbox still owns the technical integration path
- tenant owns the collecting account
- Ballbox should provide guided setup, not heavy day-to-day support

## Why tenant-direct collection should still run through Ballbox
If Adidas/client collection is done outside Ballbox, Ballbox loses:
- unified TCN adapter behavior
- unified webhook and persistence behavior
- centralized debugging for payment-approved-but-no-vend cases
- shared analytics/reporting across machines
- cleaner future migration paths

The better boundary is:
- Ballbox owns the payment orchestration path
- tenant owns the payment account

## Architecture direction

### Core rule
Payment ownership should be resolved per machine or per contract, not globally.

### Required model concept
Each machine should resolve to something like:
- `paymentOwnerMode = BALLBOX | TENANT`
- payment config reference for Mercado Pago
- vending machine identity
- owning club/venue or tenant/customer relationship

### Provider-layer implication
Ballbox needs to choose the right Mercado Pago credentials/config before creating the order and before fetching webhook-triggered order details.

### Webhook implication
Keep one Ballbox webhook endpoint:
- `/notification/mercadopago`

But Ballbox must be able to determine which payment config applies when an event arrives.
That likely means preserving enough correlation to map:
- provider order / external reference -> vending machine -> payment owner mode -> MP config

## TCN integration direction
- TCN remains the machine-facing protocol.
- The machine should render the buyer-facing QR.
- Ballbox should implement the TCN payment adapter over the native Mercado Pago provider layer.
- The Ballbox admin QR page remains a test/debug harness, not the production machine UX.

Related docs:
- `docs/tcn-payments-integration-plan.md`
- `docs/tcn-payments-open-questions.md`
- `docs/tcn-payments-execution-plan.md`

## Rollout phases

### Phase 0. Provider proof
Goal:
- prove Ballbox native Mercado Pago order + webhook persistence works publicly

Output:
- one real approved payment persisted locally

Related work:
- `OPS-1`
- `docs/mercadopago-webhook-replay-notes-2026-04-23.md`

### Phase 1. TCN contract closure
Goal:
- confirm TCN `CodeUrl` and approval/dispense handshake details with sales/engineering

Output:
- precise adapter contract

Related work:
- `PAY-3`
- `docs/tcn-payments-open-questions.md`

### Phase 2. Single technical path with two payment-owner modes
Goal:
- support the same machine flow for both Ballbox-collected and tenant-collected machines

Output:
- machine-level payment owner resolution
- machine-facing TCN adapter over provider layer
- webhook handling that can resolve the correct config

### Phase 3. Guided onboarding for first five machines
Goal:
- launch 3 club machines and 2 Adidas rental machines

Outputs:
- 3 machines on `BALLBOX`
- 2 machines on `TENANT`
- setup checklist followed per machine
- real payment test per machine/account context

### Phase 4. Informal settlement ops for Ballbox-collected clubs
Goal:
- settle club share simply without blocking rollout

Output:
- lightweight manual ledger/export/notes process

### Phase 5. Re-evaluate automation later
Goal:
- only after machine flow is stable, volume increases, or settlement pain becomes real

Possible future paths:
- better internal settlement tooling
- Mercado Pago split / marketplace if it fits the later buyer flow

## Onboarding plan

### Shared machine onboarding
For every machine:
1. identify machine owner mode: `BALLBOX` or `TENANT`
2. map machine to club/venue or tenant contract
3. map machine identifier between TCN and Ballbox
4. confirm product/pricing setup
5. confirm public webhook reachability from Ballbox
6. run one real payment test
7. confirm approval persistence and vend outcome once hardware exists

### Club-machine onboarding (`BALLBOX`)
Needed now for the first 3 machines:
- confirm machine belongs to one club/venue
- confirm commercial revenue-share terms outside code
- confirm Ballbox account is the collecting account
- note settlement percentage/rule outside the provider path
- after launch, settle informally on a fixed cadence

### Adidas/client onboarding (`TENANT`)
Needed now for the first 2 machines:
- confirm they want to collect in their own Mercado Pago account
- guide them through MP setup only enough to make the machine flow work
- confirm they configure Ballbox webhook endpoint in their MP account if required by the final provider setup
- confirm any required token/POS/external POS values
- run one real payment test with their account
- do not promise heavy ongoing support for their Mercado Pago operations

## Operational expectations
- Manual settlement is acceptable for Ballbox-collected club machines in the first wave.
- For tenant-collected machines, Ballbox is facilitating setup, not owning their payout operations.
- No promise exists that clubs must collect directly in their own account.
- Clubs mainly care about net outcome and avoiding extra invoicing burden, not about ownership of the payment rails themselves.

## Risks
### Technical
- TCN approval/dispense handshake still needs confirmation
- tenant-specific webhook/config resolution may require extra correlation fields

===== implemented-payments.md =====
# Payments Implemented State

## Current Split
- Ballbox owns the admin surface, native MercadoPago webhook intake, and native QR order creation.
- `/notification/mercadopago` is the first-party MercadoPago QR webhook route that fetches the upstream order, ignores unsupported merchant-order topics, and persists approved orders.
- `/api/integrations/payments/orders` is the first-party QR order creation route.
- `/api/integrations/payments/sessions` lists Ballbox-local approved payment records plus native MercadoPago config status.
- `/admin/payments` now manages local approved payment sessions directly for reconciliation/correction and also generates live MercadoPago QR orders for arbitrary amounts or product-priced orders.
- The admin QR generator should now be treated as an operator test/debug harness for Mercado Pago and webhook validation, not as the final buyer-facing vending-machine payment UX.
- The QR generator accepts money values in major units with decimals (for example `15.00` or `1000.00`) and converts them to Mercado Pago minor units before submission.

## APIs
- `/api/admin/payments/operations`
- `/api/admin/payments/sessions`
- `/api/admin/payments/sessions/[sessionId]`
- `/api/integrations/payments/health`
- `/api/integrations/payments/sessions`
- `/api/integrations/payments/orders`
- `/notification/mercadopago`

## Persistence
- Ballbox persists approved payment records as `PaymentSession` rows in Ballbox Postgres.
- Native MercadoPago webhook intake fetches the upstream order, maps approved orders into the canonical Ballbox payment shape, and persists them locally.
- QR Code notifications use the upstream order fetch plus canonical-reference mapping as the acceptance gate.
- Admin operators can now create, update, and delete local `PaymentSession` rows for reconciliation.
- Post-`pnpm db:push` plus `pnpm db:seed` verification confirms Ballbox Postgres keeps canonical `PaymentSession.vendingMachineId` and does not expose a `PaymentSessionRef` table or `machineId` compatibility column.
- Payments admin session routes now share Prisma error classification through `lib/prisma-errors.ts` instead of importing those helpers from `lib/ballbox-store.ts`.
- Playwright now covers local `/admin/payments` create, edit, and delete flows with deterministic cleanup of E2E `PaymentSession` rows.

## Integration Contract
- Ballbox native MercadoPago webhook path is `/notification/mercadopago`.
- Ballbox native QR order creation path is `/api/integrations/payments/orders`.
- For the current Ballbox Mercado Pago account/API surface, QR order create relies on the account-level webhook configuration instead of sending inline `notification_url` in the order payload, because Mercado Pago rejects that field on `POST /v1/orders` for this setup.
- That route accepts an explicit amount for arbitrary charges or falls back to the Ballbox `Product.priceMinor` when the amount is omitted, which powers per-product QR generation in the admin UI.
- The order route rejects values below Mercado Pago's minimum charge (`15.00 ARS`) before calling the provider.
- QR webhook persistence now depends on the upstream order fetch plus canonical-reference mapping; merchant-order topic events are ignored.
- Legacy approved-callback path `/api/integrations/payments/approved` is removed as an operational integration and now returns `410 PAYMENTS_APPROVED_CALLBACK_REMOVED`.
- Native payment correlation requires canonical `externalReference` values shaped as `payment-vm_{vendingMachineId}-txn_{machineTxnId}`.
- `NEXT_PUBLIC_SITE_URL` is required if Ballbox should expose a concrete `recommendedMercadoPagoWebhookUrl`.

## Validation Status
- Host app now owns the native MercadoPago order creation + webhook persistence path inside Ballbox.
- Real-world validation is now closed: one real public webhook and one real approved payment were persisted and verified in `/admin/payments` on 2026-05-13.
- Live MercadoPago payload quirks handled during closure: `topic_merchant_order_wh` remains intentionally ignored, `items[0].external_code` is accepted as product-id fallback, and `total_amount` is parsed from either string or number before persistence.
- Club revenue share is currently handled through scheduled manual settlements/bookkeeping for Ballbox-collected machines; no provider-native split payout path is live.
- First rollout planning now assumes one shared technical flow with two payment-owner modes: `BALLBOX` for club machines Ballbox collects on, and `TENANT` for client-owned collection setups such as Adidas rental machines; see `docs/payments-machine-rollout-rfc.md`.
- The admin surface includes a live QR generator preview for provider-level scan-and-pay validation, but production vending flow should move behind the TCN machine protocol instead of relying on that admin page.
- The webhook route is fetch-first: the webhook is just the trigger, and Ballbox verifies the order state by fetching Mercado Pago before persisting.
- TCN protocol review indicates the `additional hardware devices` warning applies to machine-side QR scanning, while the payment flow (`FunCode=8000`) returns `CodeUrl` for machine-screen QR display; see `docs/tcn-payments-integration-plan.md` and `test-results/tcn-payment-protocol/findings-2026-04-23.md`.
- Recent replay validation against two older live `ORD...` ids returned `MERCADOPAGO_ORDER_NOT_APPROVED_expired`; see `docs/mercadopago-webhook-replay-notes-2026-04-23.md` when resuming webhook persistence checks.

## Manual E2E Result
- End-to-end payment validation succeeded against Ballbox native MercadoPago webhook configuration.
- Confirmed setup used:
  - Ballbox `BALLBOX_MERCADOPAGO_ACCESS_TOKEN`
  - Ballbox `BALLBOX_MERCADOPAGO_WEBHOOK_SECRET`
  - Ballbox `BALLBOX_MERCADOPAGO_EXTERNAL_POS_ID`
  - public HTTPS webhook endpoint `/notification/mercadopago`
- Confirmed outcome:
  - a real payment was approved upstream
  - MercadoPago reached Ballbox webhook publicly
  - Ballbox fetched order details and recorded the approved payment locally
  - a `PaymentSession` row was persisted locally
  - the session was visible in `/admin/payments`

===== screen-runtime-delivery-investigation.md =====
# Screen Runtime Delivery Investigation

## Question
- TVs with limited connectivity should not have to download the broader Ballbox Next runtime just to play scheduled media.

## Current State
- Historical baseline: `/screens/[screenId]` was rendered from the Ballbox Next host app through a client component in `components/screen-player.tsx`.
- Current production direction: `/player/[screenId]` is served from Ballbox as plain HTML + JavaScript.
- Runtime behavior already depends mostly on browser primitives:
  - `fetch`
  - `CacheStorage`
  - `URL.createObjectURL`
  - `setInterval`
  - `localStorage`
  - `<video>`
- Measured current client chunks for the legacy `/screens/[screenId]` build:
  - `/_next/static/chunks/050hxdgi1a4mo.js`: 5,786 bytes
  - `/_next/static/chunks/15f4hissf3db_.js`: 54,628 bytes
  - `/_next/static/chunks/0-mbqwx08vb4q.js`: 13,855 bytes
  - total known route client JS: 74,269 bytes uncompressed
- That number excludes HTML, RSC payload, request overhead, and future shared-chunk drift.

## Why This Matters
- TVs are a constrained runtime, not a general app surface.
- Hydration and app-router plumbing add bytes and moving parts without helping actual playback.
- A player that is mostly timers, fetches, cache operations, and a `<video>` element is a poor fit for a framework-heavy delivery path when connectivity is the bottleneck.

## Constraints To Keep
- Ballbox should remain the source of truth for:
  - `/api/tvs/manifest/[screenId]`
  - `/api/tvs/heartbeat`
  - `/api/tvs/impression`
- Existing DB ownership, contracts, and admin flows should stay in Ballbox.
- Offline cache/object-URL behavior must remain first-class.
- Diagnostics for real-device verification should remain available.

## Options
### Option A
- Keep the current Next page.
- Pros:
  - no migration work
  - shared tooling and test setup
- Cons:
  - still ships Next/React client runtime to TVs
  - hydration cost remains
  - weakest fit for low-connectivity devices

### Option B
- Keep Ballbox APIs, but replace the screen page with a minimal HTML + vanilla JS player shell.
- Delivery shapes:
  - static shell under `public/`
  - or a dedicated `route.ts` HTML response that does not participate in layouts/client-side navigation
- Pros:
  - best byte reduction without creating another service
  - no React hydration requirement
  - runtime can be tuned directly for kiosk behavior
  - Ballbox still owns deployment and APIs
- Cons:
  - requires extracting runtime logic out of React component state/hooks
  - separate test surface for the lightweight shell

### Option C
- Split the player into a separate static app/repo/deployment.
- Pros:
  - strongest isolation from host app complexity
  - can optimize caching/CDN/deploy cadence independently
- Cons:
  - extra deployment surface
  - duplicated operational/debug burden
  - more auth/config coordination
  - likely unnecessary before Option B is tried

### Option D
- Keep React, but move the player into a separate lightweight SPA.
- Pros:
  - some UI ergonomics preserved
- Cons:
  - still ships framework/runtime bytes
  - weaker payoff than Option B
  - adds build complexity without removing the main problem

## Recommendation
- Choose Option B.
- Keep Ballbox as the API/backend host.
- Build a minimal player shell that uses plain browser APIs and no Next app-router/client-component runtime on the device path.
- Keep the runtime surface focused on the lightweight player.

## Suggested Shape
1. Extract playback/cache/reporting logic from `ScreenPlayer` into framework-agnostic modules.
2. Serve a dedicated player shell for TVs:
   - candidate path: `/player/[screenId]`
   - implementation: HTML response plus one small ES module
3. Reuse the current Ballbox APIs unchanged.
4. Keep the diagnostics panel in the lightweight shell.
5. Legacy `/screens/[screenId]` path removed in favor of `/player/[screenId]`.

## Migration Notes
- Start by extracting logic, not by creating a new deployment.
- Preserve Playwright coverage by pointing the offline/runtime specs at the new shell once ready.
- Do not move manifest/reporting/auth logic out of Ballbox in the same step.
- Treat the TV runtime as an explicit repo-level exception: inside Ballbox, but outside the Next client runtime.

## Sources
- Next.js route handlers: https://nextjs.org/docs/app/getting-started/route-handlers-and-middleware
- Next.js server/client component model: https://nextjs.org/docs/app/getting-started/server-and-client-components
- Next.js navigation behavior: https://nextjs.org/docs/app/getting-started/linking-and-navigating
- MDN CacheStorage: https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage
- Workbox runtime caching overview: https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/


**Evaluating document extraction**

I’m thinking I need to extract more detailed lines from the relevant documents. I should identify older documents, particularly TCN payment ones, as they might be invalidated by newer information. The suggestions for platform changes seem broader than just payments, potentially including ads, Android, and machine management. I need a plan for this. I might also need to inspect the index or other documents to find anything mentioning TCN or OurVend.

grep -RInE 'TCN|OurVend|EasyCoin|BillWallet|vending|MachineID|CodeUrl|NotityUrl|ourvend' /home/sebas/work/projects/ballbox/docs --include='*.md' | sed 's#^/home/sebas/work/projects/ballbox/docs/##' | sort

python - <<'PY'
from zipfile import ZipFile
from pathlib import Path
import re
base=Path('/home/sebas/work/projects/ballbox/docs/tcn-maquinas-recibido-2026-05-26')
keywords=['CodeUrl','NotityUrl','8000','4000','OurVend','EasyCoin','BillWallet','AdvertRemote','FTP','qrc.ourvend.com','ImageGoods','v3Skins','SQLite','ttyS2','server','4150','MachineID','slot','stock','price','QR','MercadoPago']
for p in sorted(base.glob('*.docx')):
    with ZipFile(p) as z:
        data=z.read('word/document.xml').decode('utf-8','ignore')
    text=re.sub(r'</w:p>', '\n', data)
    text=re.sub(r'<[^>]+>', '', text)
    text=text.replace('&','&').replace('<','<').replace('>','>')
    lines=[ln.strip() for ln in text.splitlines() if ln.strip()]
    print('===== '+p.name+' =====')
    for i,ln in enumerate(lines,1):
        if any(k.lower() in ln.lower() for k in keywords):
            start=max(0,i-2); end=min(len(lines),i+3)
            print(f'-- line {i}')
            for j in range(start,end):
                print(lines[j])
            print()
PY


ballbox-db-plan.md:55:4. Payments now persist canonical `vendingMachineId` and `productId` foreign keys.
ballbox-db-plan.md:56:5. Post-`pnpm db:push` plus `pnpm db:seed` verification against Ballbox Postgres confirms physical tables still expose canonical `Screen.vendingMachineId`, `Impression.tvDeviceId`, and `PaymentSession.vendingMachineId`.
domain-model-target.md:23:  - optional: `vendingMachineId`
domain-model-target.md:35:  - required: `vendingMachineId`
implemented-host-app.md:23:- Native payment persistence validates canonical `payment-vm_{vendingMachineId}-txn_{machineTxnId}` references before writing local approved sessions.
implemented-host-app.md:39:- Network now has DB-backed admin CRUD for ATC-linked clubs, venues, and vending machines.
implemented-network.md:14:- Vending-machine route handlers now call `lib/network-backend-vending-machines.ts` directly and use `lib/prisma-errors.ts` for unique-constraint classification.
implemented-network.md:5:- Ballbox owns the canonical shared `network` model for venues, vending machines, screens, and tv devices; clubs are now ATC-sourced via `atcSportclubId` and hydrated at runtime.
implemented-network.md:7:- Current network CRUD covers clubs, venues, and vending machines.
implemented-payments.md:26:- Post-`pnpm db:push` plus `pnpm db:seed` verification confirms Ballbox Postgres keeps canonical `PaymentSession.vendingMachineId` and does not expose a `PaymentSessionRef` table or `machineId` compatibility column.
implemented-payments.md:38:- Native payment correlation requires canonical `externalReference` values shaped as `payment-vm_{vendingMachineId}-txn_{machineTxnId}`.
implemented-payments.md:47:- The admin surface includes a live QR generator preview for provider-level scan-and-pay validation, but production vending flow should move behind the TCN machine protocol instead of relying on that admin page.
implemented-payments.md:49:- TCN protocol review indicates the `additional hardware devices` warning applies to machine-side QR scanning, while the payment flow (`FunCode=8000`) returns `CodeUrl` for machine-screen QR display; see `docs/tcn-payments-integration-plan.md` and `test-results/tcn-payment-protocol/findings-2026-04-23.md`.
implemented-payments.md:9:- The admin QR generator should now be treated as an operator test/debug harness for Mercado Pago and webhook validation, not as the final buyer-facing vending-machine payment UX.
implemented-tvs.md:65:- Post-`pnpm db:push` plus `pnpm db:seed` verification confirms Ballbox Postgres keeps canonical `Screen.vendingMachineId` and `Impression.tvDeviceId`, with no legacy `deviceId` column reintroduced.
payments-club-settlement-strategy.md:15:- Each vending machine belongs to one club/venue or tenant contract.
payments-club-settlement-strategy.md:32:- vendingMachineId
payments-club-settlement-strategy.md:5:- Do not force Mercado Pago split payments into the current vending QR flow.
payments-club-settlement-strategy.md:63:- current QR vending flow does not map cleanly
payments-machine-implementation-rfc.md:116:- `vendingMachineId`
payments-machine-implementation-rfc.md:156:- return Ballbox-normalized result for either admin or TCN routes
payments-machine-implementation-rfc.md:161:  vendingMachineId,
payments-machine-implementation-rfc.md:168:resolvePaymentOwnerForMachine(vendingMachineId)
payments-machine-implementation-rfc.md:173:## 7. TCN route should sit on top of the machine-payment service
payments-machine-implementation-rfc.md:175:- do not embed MP logic directly in TCN route handlers
payments-machine-implementation-rfc.md:176:- TCN route should translate between TCN contract and Ballbox machine-payment service only
payments-machine-implementation-rfc.md:182:- parse TCN request
payments-machine-implementation-rfc.md:185:- return TCN response shape including `CodeUrl`
payments-machine-implementation-rfc.md:193:- TCN adapter becomes the real machine entrypoint
payments-machine-implementation-rfc.md:208:- machine owner config stored in a local mapping module keyed by `vendingMachineId`
payments-machine-implementation-rfc.md:227:2. derive `vendingMachineId`
payments-machine-implementation-rfc.md:257:Add TCN adapter route using the same service.
payments-machine-implementation-rfc.md:266:- TCN init route returns expected TCN response shape
payments-machine-implementation-rfc.md:281:- exact TCN `CodeUrl` payload expectation
payments-machine-implementation-rfc.md:282:- exact TCN payment-success / dispense handshake
payments-machine-implementation-rfc.md:33:- machine-facing TCN adapter does not exist yet
payments-machine-implementation-rfc.md:82:- temporary in-code or env-backed mapping by `vendingMachineId`
payments-machine-implementation-rfc.md:89:- `payment-vm_{vendingMachineId}-txn_{machineTxnId}`
payments-machine-implementation-rfc.md:95:- `vendingMachineId`
payments-machine-implementation-rfc.md:9:- serves TCN machines
payments-machine-rollout-rfc.md:111:- provider order / external reference -> vending machine -> payment owner mode -> MP config
payments-machine-rollout-rfc.md:113:## TCN integration direction
payments-machine-rollout-rfc.md:114:- TCN remains the machine-facing protocol.
payments-machine-rollout-rfc.md:116:- Ballbox should implement the TCN payment adapter over the native Mercado Pago provider layer.
payments-machine-rollout-rfc.md:137:### Phase 1. TCN contract closure
payments-machine-rollout-rfc.md:139:- confirm TCN `CodeUrl` and approval/dispense handshake details with sales/engineering
payments-machine-rollout-rfc.md:154:- machine-facing TCN adapter over provider layer
payments-machine-rollout-rfc.md:188:3. map machine identifier between TCN and Ballbox
payments-machine-rollout-rfc.md:219:- TCN approval/dispense handshake still needs confirmation
payments-machine-rollout-rfc.md:21:- TCN machine integration and Mercado Pago webhook persistence are still the highest-risk technical pieces.
payments-machine-rollout-rfc.md:237:- TCN machine-facing contract is documented and implemented without guessing
payments-machine-rollout-rfc.md:29:- TCN machine payment adapter
payments-machine-rollout-rfc.md:4:- Proposed operating plan for the first vending rollout.
payments-machine-rollout-rfc.md:5:- Use this as the master document for payment ownership modes, TCN integration, onboarding, and rollout sequencing.
payments-machine-rollout-rfc.md:80:- unified TCN adapter behavior
payments-machine-rollout-rfc.md:8:- Use one Ballbox-controlled technical flow for all vending machines.
payments-machine-rollout-rfc.md:99:- vending machine identity
tcn-payments-execution-plan.md:19:## Step 2. Ask TCN the machine-contract questions
tcn-payments-execution-plan.md:1:# TCN payments execution plan
tcn-payments-execution-plan.md:26:  - send the question list to the TCN sales contact
tcn-payments-execution-plan.md:30:  - `CodeUrl` meaning and payment-success handshake are confirmed
tcn-payments-execution-plan.md:32:## Step 3. Freeze Ballbox-TCN contract
tcn-payments-execution-plan.md:38:  - define request/response schema for TCN `8000`
tcn-payments-execution-plan.md:46:- Goal: add the TCN-facing Ballbox endpoints over existing Mercado Pago primitives.
tcn-payments-execution-plan.md:4:Ordered execution plan for getting from current Ballbox native Mercado Pago support to real TCN machine payments.
tcn-payments-execution-plan.md:51:  - map TCN requests to Ballbox/Mercado Pago order creation
tcn-payments-execution-plan.md:52:  - map approved-payment state back into TCN success flow
tcn-payments-execution-plan.md:58:- Goal: verify actual stock TCN machine behavior.
tcn-payments-execution-plan.md:7:- Goal: prove Ballbox native Mercado Pago flow works end to end without TCN hardware.
tcn-payments-integration-plan.md:11:  - machine sends `MachineID`, `TradeNo`, `SlotNo`, `Price`, `NotityUrl`
tcn-payments-integration-plan.md:12:  - server returns `CodeUrl`, `TradeNo`
tcn-payments-integration-plan.md:13:- `CodeUrl` is described as the returned value used to generate the QR code.
tcn-payments-integration-plan.md:17:1. Buyer selects product on TCN machine.
tcn-payments-integration-plan.md:18:2. TCN machine requests Ballbox payment session using the TCN payment contract.
tcn-payments-integration-plan.md:1:# TCN payments integration plan
tcn-payments-integration-plan.md:20:4. Ballbox maps the Mercado Pago output into the TCN response shape and returns `CodeUrl`.
tcn-payments-integration-plan.md:21:5. TCN machine renders the QR on its screen.
tcn-payments-integration-plan.md:25:9. TCN machine receives the success signal through the TCN-side notify/result path and dispenses product.
tcn-payments-integration-plan.md:29:- Define a Ballbox route for TCN `8000` payment-init requests.
tcn-payments-integration-plan.md:31:  - `MachineID` -> Ballbox `vendingMachineId` or external machine identifier
tcn-payments-integration-plan.md:35:  - `NotityUrl`
tcn-payments-integration-plan.md:36:  - response `CodeUrl`
tcn-payments-integration-plan.md:37:- Confirm whether TCN expects raw payment URL, QR payload string, or a specific provider deep link in `CodeUrl`.
tcn-payments-integration-plan.md:40:- Map how Ballbox should signal payment success back into the TCN flow.
tcn-payments-integration-plan.md:41:- Verify whether Ballbox must call `NotityUrl`, expose a callback endpoint, or rely on a polling/result interface in the broader TCN protocol set.
tcn-payments-integration-plan.md:42:- Confirm how TCN links approved payment to dispense using `TradeNo` and/or `SlotNo`.
tcn-payments-integration-plan.md:45:- Decide the canonical mapping between TCN `MachineID` and Ballbox `VendingMachine`.
tcn-payments-integration-plan.md:4:- Treat the current `/admin/payments` QR generator as an operator test harness, not the final production payment UX for vending machines.
tcn-payments-integration-plan.md:54:- Do not frame it as the final vending-machine payment UX.
tcn-payments-integration-plan.md:57:- Exact payload expected inside TCN `CodeUrl`.
tcn-payments-integration-plan.md:58:- Exact success callback / notify shape between Ballbox and TCN after payment approval.
tcn-payments-integration-plan.md:5:- Production vending flow should integrate with the TCN machine protocol and let the machine render the buyer-facing QR on its own screen.
tcn-payments-integration-plan.md:60:- Whether TCN needs additional payment-status endpoints beyond `8000` for a full dispense flow.
tcn-payments-integration-plan.md:63:- Next implementation slice should be a TCN adapter spec + stub endpoints, not more work on the standalone admin QR page.
tcn-payments-integration-plan.md:8:- TCN protocol `2.5V` states: `to scan QR codes additional hardware devices are necessary.`
tcn-payments-open-questions.md:13:   - Ballbox calls the request `NotityUrl`
tcn-payments-open-questions.md:14:   - machine polls another TCN endpoint
tcn-payments-open-questions.md:17:3. Is `NotityUrl` always machine-provided per transaction, or is there also a machine-level configured callback?
tcn-payments-open-questions.md:1:# TCN payments open questions
tcn-payments-open-questions.md:24:6. Does the stock TCN app render the QR natively after a successful `8000` response, or is any machine-side UI configuration required?
tcn-payments-open-questions.md:31:1. Which returned value from Ballbox should be safest to map into TCN `CodeUrl` for dynamic QR display?
tcn-payments-open-questions.md:4:Close the remaining machine-integration unknowns before Ballbox implements the full TCN adapter.
tcn-payments-open-questions.md:6:## Questions for TCN sales / engineering
tcn-payments-open-questions.md:7:1. In `FunCode=8000`, what exact value should Ballbox return in `CodeUrl`?


===== PARTE 1 - DOCUMENTACION MAESTRA DE INVESTIGACION Y OPERACION.docx =====
-- line 3
DOCUMENTACIÓN MAESTRA DE INVESTIGACIÓN Y OPERACIÓN
Máquinas Expendedoras TCN / OurVend
Versión 1.0 (Bitácora completa)
PROPÓSITO DEL DOCUMENTO
Este documento existe para evitar perder conocimiento.

-- line 30
Integrar medios de pago.
Evaluar independencia futura respecto de OurVend.
Al comenzar la investigación prácticamente no existía conocimiento operativo sobre la plataforma.
Actualmente:
CONFIRMADO:

-- line 37
Acceso backstage.
Configuración de slots.
Prueba de motores.
Prueba de expulsión.
Conexión OurVend.

-- line 40
Prueba de expulsión.
Conexión OurVend.
Modificación remota de stock.
Modificación remota de precios.
Importación USB.

-- line 41
Conexión OurVend.
Modificación remota de stock.
Modificación remota de precios.
Importación USB.
Publicidad por imágenes.

-- line 48
Exportación de logs.
Exportación de base SQLite.
Integración EasyCoin.
Integración BillWallet.
Cobro real con liberación de producto.

-- line 49
Exportación de base SQLite.
Integración EasyCoin.
Integración BillWallet.
Cobro real con liberación de producto.
PENDIENTE:

-- line 50
Integración EasyCoin.
Integración BillWallet.
Cobro real con liberación de producto.
PENDIENTE:
Traducción completa.

-- line 54
Traducción completa.
Comprensión completa de ImageGoods.
Comprensión completa de Text.
Comprensión completa de v3Skins.
Publicidad remota online.

-- line 56
Comprensión completa de Text.
Comprensión completa de v3Skins.
Publicidad remota online.
Comprensión protocolo TCP.
Posible backend propio.

-- line 72
Puerto serie principal:
/dev/ttyS2
Baud rate:
9600
Servidor configurado:

-- line 76
Servidor configurado:
qrc.ourvend.com
Puerto configurado:
4150
Aplicación Android observada:

-- line 78
Puerto configurado:
4150
Aplicación Android observada:
TCN-SD-05-V1.0.0.13-20251210.01
Android:

-- line 89
Luego de múltiples pruebas se concluye que la arquitectura parece dividirse en tres componentes:
OurVend
Responsable de:
nube
stock

-- line 92
nube
stock
precios
sincronización
monitoreo

-- line 110
Esquema simplificado:
OurVend Cloud
↓
Android TCN
↓

-- line 149
La máquina posee antena.
EasyCoin posee antena independiente.
Ambos dispositivos se encuentran dentro de estructura metálica.
Hipótesis:
La estructura puede degradar señal.

-- line 159
□ evaluar antena externa
INVESTIGACIÓN DE SLOTS
Primer hallazgo importante:
Slot Management funciona correctamente.
Se pudieron:

-- line 161
Primer hallazgo importante:
Slot Management funciona correctamente.
Se pudieron:
probar motores
probar canales

-- line 202
Nunca asumir.
QR LEGAL
Existe QR provisto por despachante.
Debe pegarse:
detrás de la heladera.

-- line 203
QR LEGAL
Existe QR provisto por despachante.
Debe pegarse:
detrás de la heladera.
Agregar al checklist obligatorio.

-- line 207
Agregar al checklist obligatorio.
No entregar máquina sin QR colocado.
OURVEND
URLs observadas:
PC:

-- line 208
No entregar máquina sin QR colocado.
OURVEND
URLs observadas:
PC:
https://os.ourvend.com/Account/Login

-- line 211
PC:
https://os.ourvend.com/Account/Login
H5:
https://oshw.ourvend.com/Account/HLogin
FUNCIONES CONFIRMADAS EN OURVEND

-- line 213
H5:
https://oshw.ourvend.com/Account/HLogin
FUNCIONES CONFIRMADAS EN OURVEND
Se confirmó:
modificación remota de stock

-- line 214
https://oshw.ourvend.com/Account/HLogin
FUNCIONES CONFIRMADAS EN OURVEND
Se confirmó:
modificación remota de stock
modificación remota de precio

-- line 216
Se confirmó:
modificación remota de stock
modificación remota de precio
sincronización con máquina
PRODUCTOS

===== PARTE 2 - Android USB Publicidad Exportaciones y Sistema Interno.docx =====
-- line 40
configuración de motores
configuración de slots
publicidad
exportaciones
diagnóstico

-- line 136
ImageBackground
ImageGoods
ImagePayAdvert
ImageRight
ImageScreen

-- line 144
pollFile
v3Skins
HIPÓTESIS POR CARPETA
ImageScreen
Hipótesis muy fuerte:

-- line 173
pendiente validar.
ImageGoods
Hipótesis:
imágenes de productos.
Muy importante.

-- line 183
etc.
sin depender de aprobación visual OurVend.
Estado:
sin validar.
Text

-- line 193
sin validar.
v3Skins
Hipótesis:
skins
temas

-- line 241
FORMATO
SQLite
APERTURA
Se utilizó:
DB Browser for SQLite

-- line 244
Se utilizó:
DB Browser for SQLite
TABLAS DETECTADAS
TrayInternal
TrayPreferences

-- line 255
Servidor:
qrc.ourvend.com
Puerto:
4150
Machine ID:

-- line 257
Puerto:
4150
Machine ID:
2601070188
Idioma:

-- line 271
HALLAZGO DE PUBLICIDAD REMOTA
AdvertRemote = false
RemoteAdSysType = plataforma incorporada
INTERPRETACIÓN
Existe sistema remoto de publicidad.

-- line 276
Actualmente desactivado.
HALLAZGO DE FTP
Servidor:
ad.ourvend.com
Usuario:

-- line 278
Servidor:
ad.ourvend.com
Usuario:
ysftp
Contraseña observada en configuración exportada.

-- line 280
Usuario:
ysftp
Contraseña observada en configuración exportada.
INTERPRETACIÓN
OurVend posee infraestructura para distribución de contenido.

-- line 283
INTERPRETACIÓN
OurVend posee infraestructura para distribución de contenido.
HALLAZGO DE ACTUALIZACIONES
URL observada:
tfs.android.tcnvmms.com

-- line 305
Machine ID
Slots
Precios
Stock
Estado

-- line 307
Precios
Stock
Estado
SKU
CONCLUSIÓN

-- line 313
ARQUITECTURA DETECTADA
OurVend
↓
TCP
↓

===== PARTE 3 - EasyCoin BillWallet Operacion Comercial y Arquitectura Futura.docx =====
-- line 4
PARTE 3
EasyCoin, BillWallet, Operación Comercial y Arquitectura Futura
INTRODUCCIÓN
Una vez validado el funcionamiento mecánico y la conectividad de la máquina, el siguiente objetivo fue validar el flujo real de cobro.
La empresa utilizada para pagos es:

-- line 8
La empresa utilizada para pagos es:
EasyCoin
La gestión de dispositivos y cuentas se realiza mediante:
BillWallet
INSTALACIÓN DEL DISPOSITIVO EASYCOIN

-- line 10
La gestión de dispositivos y cuentas se realiza mediante:
BillWallet
INSTALACIÓN DEL DISPOSITIVO EASYCOIN
Se recibió un dispositivo EasyCoin.
La instalación fue realizada junto con personal de la empresa.

-- line 11
BillWallet
INSTALACIÓN DEL DISPOSITIVO EASYCOIN
Se recibió un dispositivo EasyCoin.
La instalación fue realizada junto con personal de la empresa.
Resultado:

-- line 12
INSTALACIÓN DEL DISPOSITIVO EASYCOIN
Se recibió un dispositivo EasyCoin.
La instalación fue realizada junto con personal de la empresa.
Resultado:
Instalación exitosa.

-- line 21
Usuario realiza pago.
EasyCoin recibe confirmación.
Máquina libera el canal.
Producto cae correctamente.
Estado:

-- line 33
Hipótesis:
El balance visible pertenece al firmware TCN y no al flujo principal de EasyCoin.
Pendiente:
Confirmar con EasyCoin.
BILLWALLET

-- line 35
Pendiente:
Confirmar con EasyCoin.
BILLWALLET
BillWallet es la plataforma de administración utilizada por EasyCoin.
Cada dispositivo queda asociado a una cuenta BillWallet.

-- line 36
Confirmar con EasyCoin.
BILLWALLET
BillWallet es la plataforma de administración utilizada por EasyCoin.
Cada dispositivo queda asociado a una cuenta BillWallet.
Importante:

-- line 37
BILLWALLET
BillWallet es la plataforma de administración utilizada por EasyCoin.
Cada dispositivo queda asociado a una cuenta BillWallet.
Importante:
La asociación se realiza con el usuario.

-- line 38
BillWallet es la plataforma de administración utilizada por EasyCoin.
Cada dispositivo queda asociado a una cuenta BillWallet.
Importante:
La asociación se realiza con el usuario.
NO con el dispositivo.

-- line 42
NO con el dispositivo.
RELACIÓN ENTRE DISPOSITIVOS Y MERCADOPAGO
Arquitectura observada:
Dispositivo
↓

-- line 46
↓
Usuario BillWallet
↓
MercadoPago
Consecuencia:

-- line 48
↓
MercadoPago
Consecuencia:
Un usuario puede administrar múltiples dispositivos.
Todos los dispositivos cobran al mismo MercadoPago.

-- line 51
Un usuario puede administrar múltiples dispositivos.
Todos los dispositivos cobran al mismo MercadoPago.
EJEMPLO BALLBOX
Cuenta BallBox
↓

-- line 60
↓
Todos los pagos llegan a la misma cuenta MercadoPago.
VENTAJAS DEL MODELO CENTRALIZADO
BallBox recibe toda la recaudación.
Ventajas:

-- line 65
Control total de ventas.
Control total de stock.
Conciliación simplificada.
Pago mensual a clubes.
Menor riesgo de diferencias de inventario.

-- line 77
Alternativa:
Cada club crea su propio usuario BillWallet.
Cada club conecta su propio MercadoPago.
Resultado:
Los fondos llegan directamente al club.

-- line 78
Cada club crea su propio usuario BillWallet.
Cada club conecta su propio MercadoPago.
Resultado:
Los fondos llegan directamente al club.
VENTAJAS

-- line 88
Más difícil verificar ventas.
Posibilidad de discrepancias de stock.
USUARIOS ADICIONALES
BillWallet permite agregar usuarios.
Posible implementación:

-- line 90
USUARIOS ADICIONALES
BillWallet permite agregar usuarios.
Posible implementación:
Club:
Administrador Club

-- line 100
Validar si un administrador puede eliminar a otro usuario.
QR DE PAGO
Cada cuenta BillWallet genera un QR.
Proceso observado:
Configurar MercadoPago.

-- line 101
QR DE PAGO
Cada cuenta BillWallet genera un QR.
Proceso observado:
Configurar MercadoPago.
Generar QR.

-- line 103
Proceso observado:
Configurar MercadoPago.
Generar QR.
Descargar QR.
Imprimir QR.

-- line 104
Configurar MercadoPago.
Generar QR.
Descargar QR.
Imprimir QR.
Colocar QR en la máquina.

-- line 105
Generar QR.
Descargar QR.
Imprimir QR.
Colocar QR en la máquina.
OBSERVACIÓN IMPORTANTE

-- line 106
Descargar QR.
Imprimir QR.
Colocar QR en la máquina.
OBSERVACIÓN IMPORTANTE
Si cambia el MercadoPago:

-- line 107
Imprimir QR.
Colocar QR en la máquina.
OBSERVACIÓN IMPORTANTE
Si cambia el MercadoPago:
El QR cambia.

-- line 109
OBSERVACIÓN IMPORTANTE
Si cambia el MercadoPago:
El QR cambia.
Por lo tanto:
Debe reemplazarse el QR físico.

-- line 110
Si cambia el MercadoPago:
El QR cambia.
Por lo tanto:
Debe reemplazarse el QR físico.
REGLA OPERATIVA

-- line 112
Por lo tanto:
Debe reemplazarse el QR físico.
REGLA OPERATIVA
Siempre verificar:
□ QR actualizado

-- line 115
Siempre verificar:
□ QR actualizado
□ MercadoPago correcto
□ Impresión correcta
□ QR visible para usuarios

-- line 116
□ QR actualizado
□ MercadoPago correcto
□ Impresión correcta
□ QR visible para usuarios
API EASYCOIN

-- line 118
□ Impresión correcta
□ QR visible para usuarios
API EASYCOIN
Descubrimiento muy importante.
EasyCoin ofrece API.

-- line 119
□ QR visible para usuarios
API EASYCOIN
Descubrimiento muy importante.
EasyCoin ofrece API.
Credenciales disponibles:

-- line 121
Descubrimiento muy importante.
EasyCoin ofrece API.
Credenciales disponibles:
API Key
API Secret

-- line 142
↓
API EasyCoin
↓
Máquina
↓

-- line 151
ATC procesa operación.
EasyCoin recibe autorización.
Máquina libera producto.
Beneficios de socios
Socios premium reciben:

-- line 171
ANTENAS
Tanto la máquina TCN como EasyCoin poseen antenas.
Actualmente ambas permanecen dentro del gabinete.
RIESGO IDENTIFICADO
El gabinete es metálico.

-- line 187
Verificar cloud.
Configurar EasyCoin.
Configurar MercadoPago.
Descargar QR.
Colocar QR.

-- line 188
Configurar EasyCoin.
Configurar MercadoPago.
Descargar QR.
Colocar QR.
Configurar productos.

-- line 189
Configurar MercadoPago.
Descargar QR.
Colocar QR.
Configurar productos.
Configurar precios.

-- line 190
Descargar QR.
Colocar QR.
Configurar productos.
Configurar precios.
Configurar stock.

-- line 193
Configurar precios.
Configurar stock.
Configurar publicidad.
Probar todos los canales.
Realizar compra real.

-- line 198
Confirmar liberación.
Pegar QR legal detrás.
Entregar máquina.
HIPÓTESIS ESTRATÉGICA MAYOR
Actualmente:

-- line 204
↓
OurVend
↓
EasyCoin
↓

-- line 206
↓
EasyCoin
↓
BillWallet
↓

-- line 208
↓
BillWallet
↓
MercadoPago
Hipótesis futura:

-- line 210
↓
MercadoPago
Hipótesis futura:
Máquina
↓

-- line 216
↓
EasyCoin
↓
ATC
↓

-- line 223
Controlar experiencia completa.
Sin depender operativamente de OurVend.
PRÓXIMOS EXPERIMENTOS PRIORITARIOS
Analizar Text.
Analizar ImageGoods.

-- line 226
Analizar Text.
Analizar ImageGoods.
Analizar v3Skins.
Analizar Android/data/com.tcn.vending.
Obtener documentación API EasyCoin.

-- line 227
Analizar ImageGoods.
Analizar v3Skins.
Analizar Android/data/com.tcn.vending.
Obtener documentación API EasyCoin.
Probar liberación remota.

-- line 229
Analizar Android/data/com.tcn.vending.
Obtener documentación API EasyCoin.
Probar liberación remota.
Probar acreditación remota.
Capturar tráfico TCP.

===== PARTE 4 - Ingenieria Inversa Traducciones Backend Propio y Plan de Investigacion.docx =====
-- line 11
Publicidad local
OurVend
EasyCoin
BillWallet
Exportaciones

-- line 12
OurVend
EasyCoin
BillWallet
Exportaciones
Logs

-- line 13
EasyCoin
BillWallet
Exportaciones
Logs
SQLite

-- line 16
Logs
SQLite
La pregunta ya no es:
¿Cómo usar la máquina?
La pregunta pasa a ser:

-- line 33
usuarios
independientemente de OurVend.
SISTEMA DE TRADUCCIONES
Situación actual
La interfaz aparece parcialmente:

-- line 59
En:
v3Skins
Traducciones descargadas
Desde servidor.
PLAN DE INVESTIGACIÓN DE IDIOMAS

-- line 68
Analizar:
v3Skins
Paso 3
Buscar:
json

-- line 80
Máquina completamente en español.
IMAGEGOODS
Situación actual
La carpeta existe.
No se conoce función exacta.

-- line 88
Nombre:
ImageGoods
↓
Imagenes de productos
Experimento recomendado

-- line 102
vista previa
V3SKINS
Situación actual
Detectada.
No investigada.

-- line 120
TrayPreferences contiene:
AdvertRemote = false
Y también:
RemoteAdSysType
Conclusión

-- line 130
¿Desde dónde descarga?
¿Usa FTP?
¿Usa HTTP?
¿Usa servidor propio?
FTP DETECTADO

-- line 133
¿Usa servidor propio?
FTP DETECTADO
Configuración encontrada:
ad.ourvend.com
Usuario:

-- line 135
Configuración encontrada:
ad.ourvend.com
Usuario:
ysftp
Además existe contraseña configurada.

-- line 137
Usuario:
ysftp
Además existe contraseña configurada.
Interpretación
Existe infraestructura de distribución de contenido.

-- line 172
Servidor:
qrc.ourvend.com
Puerto:
4150
Los logs muestran:

-- line 174
Puerto:
4150
Los logs muestran:
conexión TCP
heartbeat

-- line 182
Precio
Stock
SKU
Estado
Preguntas abiertas

-- line 194
Filtrar:
4150
Identificar:
JSON
headers

-- line 202
Eventualmente:
BallBox podría reemplazar parcialmente OurVend.
Objetivo mínimo
Recibir:
stock

-- line 205
Recibir:
stock
ventas
estado
Objetivo máximo

-- line 210
Control completo.
EASYCOIN COMO PUENTE
EasyCoin reduce dependencia.
Porque permite:
pago externo

-- line 211
EASYCOIN COMO PUENTE
EasyCoin reduce dependencia.
Porque permite:
pago externo
liberación externa

-- line 223
↓
EasyCoin
↓
Máquina
BENEFICIOS

-- line 245
errores
stock
temperatura
conectividad
publicidad

-- line 253
WiFi
EasyCoin
Motores
Pantalla
Publicidad

-- line 258
Android
OurVend
CONOCIMIENTO NO CONFIRMADO
Todo lo siguiente sigue siendo hipótesis:
ImageGoods controla productos.

-- line 261
Todo lo siguiente sigue siendo hipótesis:
ImageGoods controla productos.
Text controla idiomas.
v3Skins controla branding.
FTP distribuye publicidad.

-- line 263
Text controla idiomas.
v3Skins controla branding.
FTP distribuye publicidad.
OTA distribuye recursos.
Puerto 4150 puede replicarse.

-- line 264
v3Skins controla branding.
FTP distribuye publicidad.
OTA distribuye recursos.
Puerto 4150 puede replicarse.
Backend propio es viable.

-- line 266
OTA distribuye recursos.
Puerto 4150 puede replicarse.
Backend propio es viable.
ESTADO FINAL DE INVESTIGACIÓN AL CIERRE DE ESTA SESIÓN
Confirmado:

-- line 273
✅ Publicidad local operativa
✅ EasyCoin operativo
✅ BillWallet operativo
✅ Exportaciones operativas
✅ Logs operativos

-- line 274
✅ EasyCoin operativo
✅ BillWallet operativo
✅ Exportaciones operativas
✅ Logs operativos
✅ SQLite operativo

-- line 277
✅ Logs operativos
✅ SQLite operativo
Pendiente:
⬜ Traducciones
⬜ Publicidad remota

-- line 281
⬜ Publicidad remota
⬜ ImageGoods
⬜ Text
⬜ v3Skins
⬜ Protocolo TCP

-- line 283
⬜ Text
⬜ v3Skins
⬜ Protocolo TCP
⬜ Backend propio
⬜ Integración completa ATC

===== PARTE 5 - Manual Operativo BallBox.docx =====
-- line 21
□ pantalla en buen estado
□ lector EasyCoin presente (si corresponde)
PRIMER ENCENDIDO
Conectar energía.
Encender máquina.

-- line 45
VALIDACIÓN DE CLOUD
Ingresar a OurVend.
Verificar:
□ máquina visible
□ comunicación activa

-- line 49
□ comunicación activa
□ stock sincronizado
□ precios sincronizados
VALIDACIÓN DE MOTORES
Ingresar:

-- line 53
Ingresar:
Slot Management
Probar:
todos los canales
sin excepción

-- line 91
visible correctamente
CARGA DE STOCK
Desde cloud.
Validar:
cantidad correcta

-- line 117
videos
EASYCOIN
Verificar:
□ dispositivo conectado
□ alimentación correcta

-- line 128
□ caída correcta
BILLWALLET
Verificar:
□ usuario correcto
□ MercadoPago correcto

-- line 131
□ usuario correcto
□ MercadoPago correcto
□ dispositivo asociado
QR DE COBRO
Descargar QR.

-- line 133
□ dispositivo asociado
QR DE COBRO
Descargar QR.
Imprimir.
Colocar en máquina.

-- line 134
QR DE COBRO
Descargar QR.
Imprimir.
Colocar en máquina.
Importante

-- line 138
Importante
Si cambia MercadoPago:
cambia QR.
QR LEGAL
Pegar detrás de heladera.

-- line 139
Si cambia MercadoPago:
cambia QR.
QR LEGAL
Pegar detrás de heladera.
Obligatorio.

-- line 140
cambia QR.
QR LEGAL
Pegar detrás de heladera.
Obligatorio.
INSTALACIÓN EN CLUB

-- line 153
Entregar.
REPOSICIÓN DE STOCK
Abrir máquina.
Contar stock real.
Comparar cloud.

-- line 155
Abrir máquina.
Contar stock real.
Comparar cloud.
Corregir diferencias.
Cargar productos.

-- line 161
Cerrar.
Actualizar stock.
FALLAS COMUNES
No aparece WiFi
Probar hotspot.

-- line 177
Verificar:
EasyCoin
BillWallet
Internet
OPERACIÓN DE 10+ MÁQUINAS

-- line 178
EasyCoin
BillWallet
Internet
OPERACIÓN DE 10+ MÁQUINAS
Registrar:

-- line 184
responsable
EasyCoin
BillWallet
QR
Machine ID

-- line 185
EasyCoin
BillWallet
QR
Machine ID
para cada máquina.

-- line 186
BillWallet
QR
Machine ID
para cada máquina.
BASE DE DATOS MAESTRA RECOMENDADA

-- line 196
Contacto
EasyCoin ID
BillWallet
Fecha instalación
Último mantenimiento

-- line 197
EasyCoin ID
BillWallet
Fecha instalación
Último mantenimiento
Observaciones

===== PARTE 6 - Ingenieria Inversa Avanzada y Autonomia Tecnologica.docx =====
-- line 9
TCN
OurVend
EasyCoin
BillWallet
La pregunta estratégica pasa a ser:

-- line 10
OurVend
EasyCoin
BillWallet
La pregunta estratégica pasa a ser:
¿Qué dependencias podemos eliminar?

-- line 11
EasyCoin
BillWallet
La pregunta estratégica pasa a ser:
¿Qué dependencias podemos eliminar?
DEPENDENCIAS ACTUALES

-- line 19
Cloud
OurVend
Actualmente obligatorio.
Pagos
EasyCoin

-- line 22
Pagos
EasyCoin
Actualmente necesario.
Cobro
MercadoPago

-- line 25
Cobro
MercadoPago
Actualmente necesario.
OBJETIVO FINAL
Arquitectura deseada:

-- line 37
Sin depender operativamente de:
OurVend
INVESTIGACIÓN DE PROTOCOLO
Hallazgo
En logs aparece:

-- line 41
En logs aparece:
qrc.ourvend.com
puerto 4150
Además aparecen:
TCPClient

-- line 42
qrc.ourvend.com
puerto 4150
Además aparecen:
TCPClient
socket connect

-- line 53
¿Cómo registra máquina?
¿Cómo sincroniza slots?
¿Cómo sincroniza stock?
¿Cómo sincroniza precios?
¿Cómo descarga publicidad?

-- line 54
¿Cómo sincroniza slots?
¿Cómo sincroniza stock?
¿Cómo sincroniza precios?
¿Cómo descarga publicidad?
CAPTURA DE TRÁFICO

-- line 64
Filtrar:
4150
Objetivos
Identificar:
JSON

-- line 71
comandos
FTP DETECTADO
Encontrado:
ad.ourvend.com
Usuario:

-- line 73
Encontrado:
ad.ourvend.com
Usuario:
ysftp
Contraseña exportada.

-- line 75
Usuario:
ysftp
Contraseña exportada.
Preguntas
¿FTP sigue activo?

-- line 78
Preguntas
¿FTP sigue activo?
¿Se puede conectar?
¿Qué directorios existen?
¿Hay carpetas por Machine ID?

-- line 85
¿Hay skins?
EXPERIMENTO FTP
Realizar desde PC.
Intentar conexión.
Objetivo:

-- line 116
Text
v3Skins
Android/data
META
Traducción completa BallBox.

-- line 120
Traducción completa BallBox.
V3SKINS
Hipótesis:
branding.
Posible contenido:

-- line 130
Reemplazar identidad china.
IMAGEGOODS
Hipótesis:
imágenes de productos.
Objetivo:

-- line 138
Hallazgo:
AdvertRemote=false
Interpretación:
Función existe.
Pregunta:

-- line 154
Mostrar:
stock
ventas
conectividad
estado

-- line 164
Objetivo máximo
Reemplazar OurVend.
EASYCOIN COMO PUENTE ESTRATÉGICO
EasyCoin permite:
liberar producto

-- line 165
Reemplazar OurVend.
EASYCOIN COMO PUENTE ESTRATÉGICO
EasyCoin permite:
liberar producto
sin intervención directa de OurVend.

-- line 166
EASYCOIN COMO PUENTE ESTRATÉGICO
EasyCoin permite:
liberar producto
sin intervención directa de OurVend.
Esto es enorme.

-- line 168
liberar producto
sin intervención directa de OurVend.
Esto es enorme.
Porque permite:
ATC

-- line 173
↓
EasyCoin
↓
Máquina
aunque OurVend siga existiendo.

-- line 176
Máquina
aunque OurVend siga existiendo.
ESCENARIO DE MEMBRESÍAS
Socio premium.
Beneficio:

-- line 182
ATC valida.
ATC llama API EasyCoin.
Máquina libera producto.
Sin pago.
ESCENARIO DE TORNEOS

-- line 201
ventas
stock
última conexión
temperatura
estado EasyCoin

-- line 204
temperatura
estado EasyCoin
estado publicidad
ALERTAS FUTURAS
Stock bajo.

-- line 207
ALERTAS FUTURAS
Stock bajo.
Temperatura fuera de rango.
Sin internet.
Sin ventas.

-- line 223
H1
ImageGoods controla imágenes.
H2
Text controla idiomas.
H3

-- line 227
H3
v3Skins controla branding.
H4
FTP distribuye publicidad.
H5

-- line 229
H4
FTP distribuye publicidad.
H5
OTA distribuye recursos.
H6

-- line 239
Analizar Text.
Analizar v3Skins.
Analizar Android/data/com.tcn.vending.
Descargar update.xml.
Investigar FTP.

-- line 242
Descargar update.xml.
Investigar FTP.
Capturar TCP.
Documentar API EasyCoin.
Probar liberación remota.

-- line 244
Capturar TCP.
Documentar API EasyCoin.
Probar liberación remota.
Diseñar dashboard BallBox.
CONCLUSIÓN GENERAL DE LA PARTE 6


Updated #1 (pending → completed)


Plan.

## 1. Reframe source of truth
Use `docs/tcn-maquinas-recibido-2026-05-26/*` as truth with 3 levels:

- `real_working_now`
  - WiFi
  - Android/backstage
  - slot config + motor test
  - OurVend stock/precio sync
  - USB import/export
  - local ads
  - SQLite/log exports
  - EasyCoin + BillWallet
  - real cobro + liberación

- `confirmed_machine_facts`
  - modelo `TCN-CSC-8C(V49)`
  - `Machine ID`
  - Android board/app
  - `qrc.ourvend.com:4150`
  - local folders like `TcnFolder`, `ImageGoods`, `Text`, `v3Skins`
  - FTP/ad infra hints
  - OTA/update hints

- `hypothesis_or_future`
  - protocolo TCP propio
  - backend Ballbox reemplazando OurVend
  - publicidad remota propia
  - branding/traducciones totales
  - integración ATC profunda
  - flujo sin dependencias de terceros

## 2. Invalidate/rework old parent docs
First targets in parent folder:

### A. Likely invalid / over-optimistic
These now look based on guessed TCN payment path, not current proven ops:

- `docs/tcn-payments-integration-plan.md`
- `docs/tcn-payments-open-questions.md`
- `docs/tcn-payments-execution-plan.md`

Reason:
- current proven payment reality is EasyCoin + BillWallet + QR físico + liberación real
- TCN `8000 / CodeUrl / NotityUrl` remains research, not operating truth

### B. Needs heavy rewrite, not delete
- `docs/payments-machine-rollout-rfc.md`
- `docs/payments-machine-implementation-rfc.md`
- `docs/implemented-payments.md`

Reason:
- Ballbox-native Mercado Pago flow may still matter
- but it is not the main machine truth today
- docs should split:
  - `real current machine payment stack`
  - `Ballbox future replacement path`

### C. Should gain machine ops truth
- `docs/index.md`
- maybe `docs/domain-model-target.md`
- maybe `docs/repo-map.md`

Need clear section:
- current vending stack
- dependency map
- what is proven vs speculative

## 3. Proposed review pass
Do review in this order:

1. Read all 6 new docs fully.
2. Extract claims into matrix:
   - claim
   - status: confirmed / inferred / hypothesis
   - evidence doc/section
   - Ballbox impact
3. Compare against parent docs.
4. Mark each parent doc:
   - keep
   - patch
   - rewrite
   - archive
5. Produce one master replacement doc:
   - `tcn-machine-truth-2026-05-26.md`
6. Then patch old docs to point at it.

## 4. Platform changes to suggest
Based on new truth, platform should likely shift toward ops-first, not protocol-first.

### Immediate product/ops layer
- machine registry with:
  - TCN Machine ID
  - OurVend account/link
  - EasyCoin device/account
  - BillWallet user/account
  - QR status
  - legal QR status
  - venue/club
- commissioning checklist per machine
- maintenance checklist
- stock reconciliation workflow
- machine notes / incidents / last test vend
- backup/export artifact storage:
  - SQLite
  - config exports
  - logs
  - ad packs

### Near-term software layer
- machine state model:
  - cloud-controlled fields
  - local Android asset fields
  - payment-provider fields
- ads/content pack manager for `TCNFolder`
- import/export audit trail
- photo-proof fields:
  - QR pegado
  - legal QR pegado
  - antenna placement
- settlement/admin support for centralized collection mode

### R&D track, separate from core ops
- EasyCoin API integration
- remote vend / benefits / memberships
- TCN TCP reverse engineering
- translation/branding replacement
- OurVend replacement path

## 5. Main doc corrections I expect
Biggest correction:

Current Ballbox docs seem to assume:
- production path = TCN machine asks Ballbox for dynamic Mercado Pago QR

New docs say proven path is:
- production path today = EasyCoin/BillWallet-managed payment with physical QR and confirmed release

So plan should change from:
- “implement TCN adapter now”

to:
- “separate current operating stack from future autonomy stack”

## 6. Output of next step
If you want, next pass I do:

- exact invalidation matrix doc-by-doc
- concrete rewrite plan per file
- platform change list ranked by business impact

No edits yet.


[telegram] a. those were in fact optimistic and tcn provides no direct support for Mercado Pago nor a general way to set up generic third party payments. Using a physical device like the essycoin one is the only current option

b. agree but ill add that only keep docs that still make sense. Deleting is also an option

c. agree

with this changes, implementation plan seems good to. focus on documenting now (including suggested future action)

docs that are meant for human intervention/decision should be html to improve readability


**Updating the plan**

I need to respond with the updated plan. I should probably mention a typo regarding “essycoin.” It seems like I should create a to-do list based on the user's instructions and make sure that the follow-up goes to the top of the to-do list first. Organizing my thoughts this way will help ensure I complete the tasks effectively. Let’s get this sorted out!

todo

Plan Ballbox TCN documentation rewrite

Document current TCN machine truth using newly received docs and user clarifications: no direct TCN Mercado Pago support, no generic third-party payments, physical payment device like EasyCoin is the only current option. Focus on documentation and suggested future actions. Human-intervention/decision docs should be HTML. No edits yet.


Created #2: Plan Ballbox TCN documentation rewrite (pending)

Plan Ballbox TCN documentation rewrite

Plan Ballbox TCN documentation rewrite