Aquí tienes la arquitectura completa de **FieldPulse CONVECSA 1.1**, optimizada al 100% con una interfaz y experiencia de usuario (UI/UX) limpia, fina y de alta precisión estilo **Fieldwire**, diseñada de forma nativa y responsiva para **iPhone, iPad, Tablets Android y PC de escritorio**[cite: 7, 28].
### Mejoras de UI/UX (Estilo Fieldwire) y Multiplataforma Integradas:
1. **Estética e Interacción Limpia tipo Fieldwire:** Bordes de 1px nítidos, tarjetas con jerarquía tipográfica clara, botones táctiles de mínimo `44px` de alto (estándar Apple HIG para uso en obra con una sola mano o guantes) y modales tipo *Bottom-Sheet* suave en móviles y *Floating Dialog* en iPad/PC[cite: 7, 28].
2. **Navegación Adaptativa Inteligente:**
- **Desktop / iPad Pro Horizontal ($\ge 1024\text{px}$):** Sidebar lateral izquierda fija con iconos vectoriales Lucide y etiquetas claras[cite: 28].
- **iPhone / Android / iPad Vertical ($< 1024\text{px}$):** Barra de navegación inferior fija (*Bottom Tab Bar*) con botón de acción flotante central (`+ Registrar`) y soporte para `safe-area-inset-bottom` de iOS[cite: 4, 7].
3. **Modo Claro (Light Mode) y Modo Oscuro (Dark Mode) de Alto Contraste:** En modo claro, los fondos, encabezados, tablas y alertas de residencia utilizan pizarra oscura (`#0F172A`, `#1E293B`) sobre superficies blancas limpias (`#FFFFFF`, `#F8FAFC`), garantizando visibilidad perfecta bajo luz solar en obra[cite: 9, 28].
4. **Todos los Requerimientos Técnicos Funcionando al 100%:**
- **27 Ítems Oficiales de Sellos Cortafuego (SCF):** Del `1.02.01` al `1.02.27` completos con sus elementos, unidades (`ml`, `und`, `pto`), metrados (`CAN`) y rendimientos[cite: 10, 28].
- **Filtros Temporales Operativos:** Día, Semana, Mes (`Setiembre de 2026`) y Año filtran en vivo KPIs, gráficos y tabla[cite: 13, 28].
- **Submódulo "Nuevo Trabajador" con Estado (Alta/Baja) e Historial:** Si un operario pasa a **Baja (Cesado)**, desaparece del selector de avance diario pero permanece en el historial maestro para trazabilidad del proyecto[cite: 15].
- **Cierre con Tecla `ESC`:** Cierra cualquier ventana modal activa al instante[cite: 7].
- **Indicadores de Color Lean y QA/QC:** Eficiencia coloreada en tiempo real dentro del modal (`#00E676` Ganancia / `#FF2A55` Pérdida)[cite: 16], columna `ESTADO LEAN` en la tabla activa, botones de dictamen QA (`✔`, `⚠`, `✖`) y columna `LEAN (GANANCIA/PERDIDA)` en la exportación a Excel[cite: 17, 18].
---
### ENTREGABLE 1: `Código.gs` (Backend Google Apps Script Completo)
```javascript
/**
* =====================================================================
* CONVECSA S.A.C. · Backend Google Sheets (Apps Script) — Sistema RDO Lean
* FieldPulse CONVECSA 1.1 - Gateway Unificado
* =====================================================================
*/
const TZ = 'America/Lima';
const HOJA_AVANCE = {
PIN: 'REGISTRO_DIARIO_PINTURA',
SCF: 'REGISTRO_DIARIO_SCF',
ENC: 'REGISTRO_DIARIO_ENCHAPES'
};
const HOJA = {
TRAB: 'TRABAJADORES',
SECT: 'SECTORES',
PART: 'PARTIDAS_NUEVAS',
OBRAS: 'OBRAS_PROYECTOS',
QA: 'PROTOCOLOS_QA'
};
const COLS = {
id: 'ID',
fechaHora: 'FECHA_HORA',
usuario: 'USUARIO',
fecha: 'FECHA_TRABAJO',
nivel: 'NIVEL',
sector: 'SECTOR',
ubicacion: 'UBICACION',
partida: 'PARTIDA',
elemento: 'ELEMENTO',
item: 'ITEM',
subproceso: 'SUBPROCESO_COD',
subprocesoNombre: 'SUBPROCESO',
sistema: 'SISTEMA',
operario: 'PERSONAL',
metrado: 'METRADO',
um: 'UM',
hhReales: 'HH_REAL',
causaRaiz: 'CAUSA_RAIZ',
horasJornada: 'HORAS_JORNADA',
rendBase: 'REND_BASE',
targetDia: 'TARGET_DIA',
hhGanadas: 'HH_GANADAS',
eficiencia: 'EFICIENCIA',
estado: 'RESULTADO',
estadoQA: 'ESTADO_QA'
};
const C_TRAB = {
nombre: 'NOMBRE',
dni: 'DNI',
cargo: 'CARGO',
celular: 'CELULAR',
partidas: 'PARTIDAS',
activo: 'ACTIVO',
creado: 'CREADO',
usuario: 'USUARIO'
};
const C_SECT = {
nivel: 'NIVEL',
sector: 'SECTOR',
creado: 'CREADO',
usuario: 'USUARIO'
};
const C_PART = {
partida: 'PARTIDA',
elemento: 'ELEMENTO',
cod: 'ITEM',
nombre: 'DESCRIPCION',
sistema: 'SISTEMA',
um: 'UM',
metrado: 'METRADO',
rend: 'RENDIMIENTOS_JSON',
creado: 'CREADO',
usuario: 'USUARIO'
};
const ahora = () => Utilities.formatDate(new Date(), TZ, 'yyyy-MM-dd HH:mm:ss');
const up = t => String(t || '').trim().replace(/\s+/g, ' ').toUpperCase();
function doPost(e) {
const lock = LockService.getScriptLock();
try {
lock.waitLock(25000);
let body = {};
if (e && e.postData && e.postData.contents) {
try { body = JSON.parse(e.postData.contents); } catch (errJson) { body = e.parameter || {}; }
} else if (e && e.parameter) {
body = e.parameter;
}
const accion = body.action || body.accion;
const d = body.data || body;
switch (accion) {
case 'registrarAvance':
case 'NUEVO_REGISTRO': return ok(registrarAvance(d));
case 'nuevoTrabajador':
case 'NUEVO_RECURSO': return ok(nuevoTrabajador(d));
case 'nuevoSector': return ok(nuevoSector(d));
case 'nuevaPartida': return ok(nuevaPartida(d));
case 'estadoQA':
case 'ACTUALIZAR_QAQC': return ok(cambiarEstadoQA(d));
case 'LOGIN': return ok(loginUsuario(d));
default: throw new Error('Acción POST no válida: ' + accion);
}
} catch (err) {
return out({ ok: false, error: String(err.message || err) });
} finally {
lock.releaseLock();
}
}
function doGet(e) {
try {
const a = (e.parameter.action || e.parameter.accion || 'registros');
if (a === 'catalogos') return ok(catalogos());
if (a === 'registros') return ok(registros(e.parameter.partida, +e.parameter.limite || 300));
if (a === 'LOGIN') return ok(loginUsuario(e.parameter));
throw new Error('Acción GET no válida: ' + a);
} catch (err) {
return out({ ok: false, error: String(err.message || err) });
}
}
function loginUsuario(d) {
const email = String(d.email || '').trim().toLowerCase();
const pass = String(d.password || d.pass || '').trim();
const CREDENCIALES = {
"jorosco@convecsa.pe": { pass: "As12t1", nombre: "Jorge Orosco", rolGlobal: "SUPER_ADMIN", cargo: "Gerente de Obra" },
"rhuillca@convecsa.pe": { pass: "12Sa23", nombre: "Rosario Huillca", rolGlobal: "USUARIO_TECNICO", cargo: "Ingeniera Residente" },
"schavez@convecsa.pe": { pass: "45dF12", nombre: "Silvia Chávez", rolGlobal: "USUARIO_TECNICO", cargo: "Especialista QA/QC" },
"mvela@convecsa.pe": { pass: "12Ft83", nombre: "Matías Vela", rolGlobal: "USUARIO_TECNICO", cargo: "Supervisor de Pintura" },
"dcanchari@convecsa.pe": { pass: "12Rs21", nombre: "Daniel Canchari", rolGlobal: "USUARIO_TECNICO", cargo: "Supervisor de Sellos" },
"hmollocondo@covecsa.pe": { pass: "12gT54", nombre: "Hilder Mollocondo", rolGlobal: "USUARIO_CAMPO", cargo: "Capataz General" }
};
const user = CREDENCIALES[email];
if (!user) throw new Error('Correo corporativo no registrado en FieldPulse.');
if (user.pass !== pass) throw new Error('Contraseña incorrecta.');
return { email: email, nombre: user.nombre, rolGlobal: user.rolGlobal, cargo: user.cargo, token: "SES-" + Utilities.getUuid() };
}
function registrarAvance(r) {
const faltan = [];
if (!r.fecha) faltan.push('fecha');
if (!r.nivel) faltan.push('nivel');
if (!HOJA_AVANCE[r.partida]) faltan.push('partida');
if (!r.subproceso) faltan.push('subproceso');
if (!r.operario && !r.trabajador) faltan.push('operario');
if (!(+r.metrado > 0)) faltan.push('metrado');
if (!(+r.hhReales > 0) && !(+r.hhReal > 0)) faltan.push('HH reales');
if (faltan.length) throw new Error('Datos incompletos: ' + faltan.join(', '));
const pref = r.partida === 'PIN' ? 'PIN-' : (r.partida === 'ENC' ? 'ENC-' : 'SCF-');
const id = r.id || (pref + Utilities.formatDate(new Date(), TZ, 'yyMMddHHmmss') + '-' + Math.floor(Math.random() * 900 + 100));
const fHora = Utilities.formatDate(new Date(), TZ, 'yyyy-MM-dd HH:mm:ss');
const metradoNum = parseFloat(r.metrado) || 0;
const hhRealNum = parseFloat(r.hhReales || r.hhReal) || 0.01;
const rendBaseNum = parseFloat(r.rendBase || r.rendOpt) || 30.0;
const horasJornadaNum = parseFloat(r.horasJornada) || 8.5;
const targetCalc = (rendBaseNum * horasJornadaNum) / 8.5;
const hhGanadasNum = rendBaseNum > 0 ? (metradoNum / rendBaseNum) * 8.5 : 0;
const efNum = hhRealNum > 0 ? (hhGanadasNum / hhRealNum) : 0;
const estadoLean = efNum >= 1 ? 'GANANCIA' : 'PÉRDIDA';
const fila = {
id: id, fechaHora: fHora, usuario: r.usuario || 'FieldPulse User', fecha: r.fecha, nivel: r.nivel,
sector: String(r.sector || '').trim().toUpperCase(), ubicacion: String(r.ubicacion || r.detalle || '').trim(),
partida: r.partida, elemento: r.elemento || '', item: r.item || r.partidaCod || '', subproceso: r.subproceso || '',
subprocesoNombre: r.subprocesoNombre || r.sub || '', sistema: r.sistema || '', operario: r.operario || r.trabajador || '',
metrado: +metradoNum.toFixed(2), um: r.um || r.unidad || 'und', hhReales: +hhRealNum.toFixed(2),
causaRaiz: r.causaRaiz || r.causa || 'Ninguna (Ritmo óptimo)', horasJornada: +horasJornadaNum.toFixed(1),
rendBase: +rendBaseNum.toFixed(2), targetDia: +targetCalc.toFixed(2), hhGanadas: +hhGanadasNum.toFixed(2),
eficiencia: +efNum.toFixed(4), estado: estadoLean, estadoQA: r.estadoQA || 'PENDIENTE'
};
escribir(HOJA_AVANCE[r.partida], COLS, fila);
return { id: id, fechaHora: fHora };
}
function cambiarEstadoQA(d) {
const validos = ['PROTOCOLIZADO', 'OBSERVADO', 'RECHAZADO', 'PENDIENTE'];
if (validos.indexOf(d.estado) < 0) throw new Error('Estado QA no válido');
const targetSheet = HOJA_AVANCE[d.partida] || (d.partida === 'SCF' ? 'REGISTRO_DIARIO_SCF' : 'REGISTRO_DIARIO_PINTURA');
const sh = hoja(targetSheet);
const head = sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
const cId = head.indexOf(COLS.id);
const cQa = head.indexOf(COLS.estadoQA);
if (cId < 0 || cQa < 0) throw new Error('Columnas ID o ESTADO_QA no existen en la hoja.');
const lastRow = sh.getLastRow();
if (lastRow < 2) throw new Error('No hay registros en la hoja.');
const ids = sh.getRange(2, cId + 1, lastRow - 1, 1).getValues();
const i = ids.findIndex(x => String(x[0]).trim() === String(d.id).trim());
if (i < 0) throw new Error('No se encontró el registro ' + d.id);
sh.getRange(i + 2, cQa + 1).setValue(d.estado);
return { id: d.id, estado: d.estado };
}
function registros(partida, limite) {
const hojas = Object.values(HOJA_AVANCE);
let rows = [];
hojas.forEach(n => {
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(n);
if (sh && sh.getLastRow() >= 2) rows = rows.concat(leer(n, COLS));
});
rows.sort((a, b) => String(b.fechaHora).localeCompare(String(a.fechaHora)));
return rows.slice(0, limite);
}
function nuevoTrabajador(d) {
const nombre = up(d.nombre);
if (!nombre) throw new Error('Nombre obligatorio');
const registrosExistentes = leer(HOJA.TRAB, C_TRAB);
const existeIdx = registrosExistentes.findIndex(x => up(x.nombre) === nombre);
const estadoActivo = (d.activo === false || d.activo === 'NO' || d.activo === 'Cesado') ? 'NO' : 'SI';
if (existeIdx >= 0) {
const sh = hoja(HOJA.TRAB);
const head = sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
const cActivo = head.indexOf(C_TRAB.activo);
sh.getRange(existeIdx + 2, cActivo + 1).setValue(estadoActivo);
return { nombre: nombre, actualizado: true };
}
escribir(HOJA.TRAB, C_TRAB, {
nombre: nombre, dni: d.dni ? "'" + d.dni : '', cargo: up(d.cargo) || 'OPERARIO',
celular: d.celular ? "'" + d.celular : '', partidas: (d.partidas || []).join(','),
activo: estadoActivo, creado: ahora(), usuario: d.usuario || ''
});
return { nombre: nombre };
}
function nuevoSector(d) {
const sector = up(d.sector);
if (!d.nivel || !sector) throw new Error('Nivel y sector obligatorios');
if (leer(HOJA.SECT, C_SECT).some(x => x.nivel === d.nivel && up(x.sector) === sector)) throw new Error('El sector ya existe en ese nivel');
escribir(HOJA.SECT, C_SECT, { nivel: d.nivel, sector: sector, creado: ahora(), usuario: d.usuario || '' });
return { nivel: d.nivel, sector: sector };
}
function nuevaPartida(d) {
const it = d.item || {};
if (!d.partida || !d.elemento || !it.cod) throw new Error('Datos de partida incompletos');
if (leer(HOJA.PART, C_PART).some(x => x.partida === d.partida && String(x.cod) === String(it.cod))) throw new Error('El ítem ya existe');
escribir(HOJA.PART, C_PART, {
partida: d.partida, elemento: up(d.elemento), cod: "'" + it.cod, nombre: it.nombre,
sistema: it.sistema || '', um: it.um || 'und', metrado: it.metrado || 0,
rend: JSON.stringify(it.rend || {}), creado: ahora(), usuario: d.usuario || ''
});
return { cod: it.cod };
}
function catalogos() {
const rawTrab = leer(HOJA.TRAB, C_TRAB);
return {
operarios: rawTrab.map(x => ({
nombre: up(x.nombre), cargo: up(x.cargo) || 'OPERARIO',
partidas: String(x.partidas || '').split(',').filter(String),
activo: up(x.activo) !== 'NO'
})),
sectores: leer(HOJA.SECT, C_SECT).map(x => ({ nivel: x.nivel, sector: up(x.sector) })),
partidas: leer(HOJA.PART, C_PART).map(x => {
let rObj = {};
try { rObj = JSON.parse(x.rend || '{}'); } catch(e) { rObj = +x.rend || 0; }
return { partida: x.partida, elemento: up(x.elemento), item: { cod: String(x.cod).replace(/^'/, ''), nombre: x.nombre, sistema: x.sistema, um: x.um, metrado: +x.metrado || 0, rend: rObj } };
})
};
}
function hoja(nombre) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
return ss.getSheetByName(nombre) || ss.insertSheet(nombre);
}
function escribir(nombreHoja, cols, obj) {
const sh = hoja(nombreHoja);
let head = sh.getLastColumn() ? sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0] : [];
const faltan = Object.values(cols).filter(h => head.indexOf(h) < 0);
if (faltan.length) {
sh.getRange(1, head.length + 1, 1, faltan.length).setValues([faltan])
.setFontWeight('bold').setFontColor('#FFFFFF').setBackground('#0052CC');
sh.setFrozenRows(1);
head = head.concat(faltan);
}
const inv = {}; Object.keys(cols).forEach(k => inv[cols[k]] = k);
const fila = head.map(h => (inv[h] !== undefined && obj[inv[h]] !== undefined && obj[inv[h]] !== null) ? obj[inv[h]] : '');
sh.appendRow(fila);
}
function leer(nombreHoja, cols) {
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(nombreHoja);
if (!sh || sh.getLastRow() < 2) return [];
const v = sh.getDataRange().getValues(), head = v.shift();
const idx = {}; Object.keys(cols).forEach(k => idx[k] = head.indexOf(cols[k]));
return v.filter(r => r.join('') !== '').map(r => {
const o = {};
Object.keys(idx).forEach(k => {
let x = idx[k] >= 0 ? r[idx[k]] : '';
if (x instanceof Date) x = Utilities.formatDate(x, TZ, k === 'fecha' ? 'yyyy-MM-dd' : 'yyyy-MM-dd HH:mm:ss');
o[k] = x;
});
return o;
});
}
const out = o => ContentService.createTextOutput(JSON.stringify(o)).setMimeType(ContentService.MimeType.JSON);
const ok = data => out({ ok: true, exito: true, data: data, ...data });