0% encontró este documento útil (0 votos)
30 vistas15 páginas

Codigogs

El documento describe un sistema de gestión de pedidos de tintas en Google Sheets, que incluye funciones para crear, aprobar y gestionar pedidos e inventarios. Se implementan menús y diálogos en la interfaz de usuario, así como la generación de informes en PDF y el envío de correos electrónicos para notificaciones. Además, se manejan errores y actualizaciones en el inventario, asegurando un control efectivo de los pedidos y existencias.

Cargado por

Christian Guzman
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como TXT, PDF, TXT o lee en línea desde Scribd

Temas abordados

  • Notificaciones Automáticas,
  • Pedidos,
  • Configuración Inicial,
  • Descuento de Inventario,
  • Cantidad de Tintas,
  • Funciones de Panel de Control,
  • Registro de Inventario,
  • Errores en Descuento,
  • Panel de Control,
  • Generación de PDF
0% encontró este documento útil (0 votos)
30 vistas15 páginas

Codigogs

El documento describe un sistema de gestión de pedidos de tintas en Google Sheets, que incluye funciones para crear, aprobar y gestionar pedidos e inventarios. Se implementan menús y diálogos en la interfaz de usuario, así como la generación de informes en PDF y el envío de correos electrónicos para notificaciones. Además, se manejan errores y actualizaciones en el inventario, asegurando un control efectivo de los pedidos y existencias.

Cargado por

Christian Guzman
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como TXT, PDF, TXT o lee en línea desde Scribd

Temas abordados

  • Notificaciones Automáticas,
  • Pedidos,
  • Configuración Inicial,
  • Descuento de Inventario,
  • Cantidad de Tintas,
  • Funciones de Panel de Control,
  • Registro de Inventario,
  • Errores en Descuento,
  • Panel de Control,
  • Generación de PDF

function myFunction() {

}
/******************************************
* CONFIGURACIÓN INICIAL Y MENÚ *
******************************************/

function onOpen() {
const ui = [Link]();
[Link]('Sistema de Tintas')
.addItem('📝 Nuevo Pedido', 'mostrarFormularioPedido')
.addItem('✅ Aprobar Pedidos', 'mostrarAprobador')
.addItem('📦 Gestión de Inventario', 'mostrarFormularioInventario')
.addItem('📊 Panel de Control', 'mostrarPanelControl')
.addSeparator()
.addItem('⚠️ Verificar Stock Crítico', 'verificarStockCritico')
.addToUi();
}

/******************************************
* FUNCIONES PARA PEDIDOS *
******************************************/

function mostrarFormularioPedido() {
const html = [Link]('FormularioPedido')
.setWidth(650)
.setHeight(750);
[Link]().showModalDialog(html, "Nuevo Pedido de Tintas");
}

function enviarPedido(formData) {
try {
// Configurar hojas
const ss = [Link]();
const hojaPedidos = [Link]("Pedidos") || crearHojaPedidos();
const hojaAprobaciones = [Link]("Aprobaciones") ||
crearHojaAprobaciones();

// Generar ID y fecha
const idPedido = generarIdPedido();
const fecha = new Date();

// Crear resumen de items


const resumen = [Link](i => `${[Link]} (${[Link]}) x $
{[Link]}`).join("\n");

// Registrar en hojas
registrarPedido(hojaPedidos, idPedido, fecha, formData, resumen);
registrarAprobacion(hojaAprobaciones, idPedido, fecha, formData, resumen);

// Generar y enviar PDF


const pdf = generarPDFDesdePlantilla(idPedido, [Link], [Link],
fecha, [Link]);
enviarEmailPedido(idPedido, [Link], resumen, [Link],
pdf);

return { success: true, message: "Pedido enviado correctamente. Se ha


notificado al equipo." };
} catch (e) {
[Link]("Error en enviarPedido: " + [Link]());
return { success: false, message: "Error al procesar el pedido: " +
[Link] };
}
}

function crearHojaPedidos() {
const ss = [Link]();
const hoja = [Link]("Pedidos");
[Link](["ID", "Fecha", "Solicitante", "Detalles", "Observaciones"]);
[Link]("A1:E1").setFontWeight("bold").setBackground("#e6e6e6");
return hoja;
}

function crearHojaAprobaciones() {
const ss = [Link]();
const hoja = [Link]("Aprobaciones");
[Link](["ID", "Fecha", "Solicitante", "Detalles", "Estado", "Fecha
Aprobación"]);
[Link]("A1:F1").setFontWeight("bold").setBackground("#e6e6e6");
return hoja;
}

function generarIdPedido() {
return "PED-" + [Link](new Date(), [Link](),
"yyyyMMdd-HHmmss");
}

function registrarPedido(hoja, id, fecha, formData, resumen) {


[Link]([id, fecha, [Link], resumen, [Link] ||
""]);
}

function registrarAprobacion(hoja, id, fecha, formData, resumen) {


[Link]([id, fecha, [Link], resumen, "Pendiente", ""]);
}

function enviarEmailPedido(id, nombre, resumen, obs, pdf) {


const destinatarios = ["cabpampa2016@[Link]", "jordanbarcelo@[Link]",
"joelrivas@[Link]", "coordimedia@[Link]"].join(",");

[Link]({
to: destinatarios,
subject: `📨 Pedido de Tintas: ${id}`,
body: `
Nuevo pedido de tintas registrado:

Solicitante: ${nombre}
Fecha: ${[Link](new Date(), [Link](),
"dd/MM/yyyy HH:mm")}

Detalles:
${resumen}

Observaciones: ${obs || "Ninguna"}

--
Sistema Automático de Pedidos
Colegio Andrés Bello - Pampa
`,
attachments: [pdf],
name: "Sistema de Pedidos"
});
}

/******************************************
* FUNCIONES DE APROBACIÓN - CORREGIDAS *
******************************************/

function mostrarAprobador() {
try {
const html = [Link]('AprobacionUI')
.setWidth(500)
.setHeight(400);
[Link]().showModalDialog(html, "Aprobar Pedidos");
} catch (e) {
[Link]("Error al mostrar aprobador: " + [Link]());
[Link]().alert("Error al cargar la interfaz de aprobación");
}
}

function obtenerPedidosPendientes() {
try {
const hoja = [Link]().getSheetByName("Aprobaciones");
if (!hoja || [Link]() <= 1) return [];

const datos = [Link](2, 1, [Link]()-1, 6).getValues();


return datos
.filter(fila => fila[4] === "Pendiente")
.map(fila => ({
id: fila[0],
fecha: [Link](fila[1], [Link](),
"dd/MM/yyyy HH:mm"),
solicitante: fila[2],
detalles: fila[3]
}));
} catch (e) {
[Link]("Error en obtenerPedidosPendientes: " + [Link]());
return [];
}
}

function aprobarPedidoPorID(idPedido) {
try {
const ss = [Link]();
const hojaAprobaciones = [Link]("Aprobaciones");
if (!hojaAprobaciones) throw new Error("No se encontró la hoja
'Aprobaciones'");

const datos = [Link]().getValues();

for (let i = 1; i < [Link]; i++) {


if (datos[i][0] === idPedido && datos[i][4] === "Pendiente") {
// 1. Actualizar estado de aprobación
const fechaAprobacion = new Date();
actualizarEstadoAprobacion(hojaAprobaciones, i, fechaAprobacion);

// 2. Descontar del inventario


const items = parsearDetalles(datos[i][3]);
const descontado = descontarDelInventario(items);

if (![Link]) {
revertirAprobacion(hojaAprobaciones, i);
throw new Error([Link]);
}

// 3. Generar y enviar documentos


const pdf = generarPDFDesdePlantilla(
idPedido,
datos[i][2],
items,
fechaAprobacion,
"Pedido aprobado y descontado del inventario"
);

enviarEmailAprobacion(idPedido, datos[i][2], items, fechaAprobacion, pdf);

// 4. Verificar stock crítico


verificarStockCritico();

return { success: true, message: `Pedido ${idPedido} aprobado


correctamente` };
}
}
throw new Error("Pedido no encontrado o ya fue procesado");
} catch (e) {
[Link]("Error en aprobarPedido: " + [Link]());
return { success: false, message: "Error al aprobar: " + [Link] };
}
}

function actualizarEstadoAprobacion(hoja, fila, fecha) {


[Link](fila+1, 5).setValue("Aprobado");
[Link](fila+1, 6).setValue(fecha);
[Link](fila+1, 1, 1, 6).setBackground("#d9ead3");
}

function revertirAprobacion(hoja, fila) {


[Link](fila+1, 5).setValue("Error al descontar");
[Link](fila+1, 1, 1, 6).setBackground("#ffcccc");
}

function enviarEmailAprobacion(id, solicitante, items, fecha, pdf) {


[Link]({
to: "cabpampa2016@[Link]",
subject: `✅ Pedido Aprobado: ${id}`,
body: `El pedido ${id} ha sido aprobado.\n\nSolicitante: ${solicitante}\nFecha:
${[Link](fecha, [Link](), "dd/MM/yyyy HH:mm")}\n\
nItems descontados:\n${[Link](i => `- ${[Link]} (${[Link]}) x $
{[Link]}`).join('\n')}\n\n--\nSistema de Gestión de Tintas`,
attachments: [pdf]
});
}

/******************************************
* FUNCIONES DE INVENTARIO - ACTUALIZADAS *
******************************************/
function mostrarFormularioInventario() {
const html = [Link]('FormularioInventario')
.setWidth(600)
.setHeight(700);
[Link]().showModalDialog(html, "Gestión de Inventario");
}

function agregarAlInventario(formData) {
try {
const hojaTintas = [Link]().getSheetByName("Tintas");
if (!hojaTintas) throw new Error("No se encontró la hoja 'Tintas'");

// Buscar si el modelo ya existe


const [filaExistente, existenciaActual] = buscarModeloEnInventario(hojaTintas,
formData);

if (filaExistente > 0) {
// Actualizar existencia existente
actualizarExistencia(hojaTintas, filaExistente, existenciaActual, formData);
} else {
// Agregar nuevo item
agregarNuevoItem(hojaTintas, formData);
}

// Generar y enviar confirmación


const pdf = generarPDFInventario(formData);
enviarEmailConfirmacionInventario(formData, pdf);

return { success: true, message: "Inventario actualizado correctamente" };


} catch (e) {
[Link]("Error en agregarAlInventario: " + [Link]());
return { success: false, message: "Error: " + [Link] };
}
}

function buscarModeloEnInventario(hoja, formData) {


const datos = [Link](2, 1, [Link]()-1, 9).getValues();

for (let i = 0; i < [Link]; i++) {


const modeloExistente = `${datos[i][1]} - ${datos[i][4]} - ${datos[i]
[5]}`.trim();
if (modeloExistente === [Link] && datos[i][2] === [Link])
{
return [i + 2, datos[i][7]]; // [fila, existenciaActual]
}
}

return [-1, 0];


}

function actualizarExistencia(hoja, fila, existenciaActual, formData) {


const nuevaExistencia = existenciaActual + [Link];
[Link](fila, 8).setValue(nuevaExistencia); // Columna H (Existencia)

// Actualizar columna "Reponer" (I) si es necesario


const stockMaximo = [Link](fila, 7).getValue() || 4;
[Link](fila, 9).setValue(nuevaExistencia < stockMaximo ? "SI" : "NO");
}
function agregarNuevoItem(hoja, formData) {
const partesModelo = [Link](' - ');
if ([Link] !== 3) throw new Error("Formato de modelo incorrecto.
Debe ser: Marca - Número - Color");

const nuevaFila = [
[Link](), // N° (columna A)
partesModelo[0], // Marca (B)
[Link], // Impresora (C)
[Link] || "Bodega", // Ubicación (D)
partesModelo[1], // Número (E)
partesModelo[2], // Color (F)
[Link] || 4, // Stock MAXIMO (G)
[Link], // Existencia (H)
[Link] < ([Link] || 4) ? "SI" : "NO" // Reponer (I)
];

[Link](nuevaFila);
}

function generarPDFInventario(formData) {
const doc = [Link](`Actualización Inventario $
{[Link](new Date(), [Link](), "yyyyMMdd-
HHmmss")}`);
const body = [Link]();

// Logo
try {
const logoUrl = "[Link]
%20BELLO%20CIR%[Link]";
const response = [Link](logoUrl);
const blob = [Link]();
[Link](blob)
.setWidth(100)
.setHeight(100)
.setAlignment([Link]);
} catch (e) {
[Link]("No se pudo cargar el logo: " + [Link]);
}

// Contenido
[Link]("COLEGIO ANDRÉS BELLO - PAMPA")
.setHeading([Link].HEADING1)
.setAlignment([Link])
.setBold(true);

[Link]("\nREGISTRO DE INVENTARIO")
.setHeading([Link].HEADING2)
.setAlignment([Link]);

[Link](`\nFecha: ${[Link](new Date(),


[Link](), "dd/MM/yyyy HH:mm")}`);

const tabla = [Link]();


const header = [Link]();
["Campo", "Valor"].forEach(text => {
[Link](text).setBackgroundColor("#dddddd").setBold(true);
});
const datos = [
["Modelo", [Link]],
["Impresora", [Link]],
["Cantidad", [Link]()],
["Ubicación", [Link] || "Bodega"],
["Stock MÁXIMO", [Link] || "4"],
["Observaciones", [Link] || "Ninguna"]
];

[Link](fila => {
const row = [Link]();
[Link](fila[0]).setBold(true);
[Link](fila[1]);
});

[Link]("\n\nResponsable:\n\n_____________________________\nNombre y
firma")
.setSpacingBefore(100);

[Link]();
[Link](3000);
return [Link]("application/pdf");
}

function enviarEmailConfirmacionInventario(formData, pdf) {


[Link]({
to: [Link]().getEmail(),
subject: `✅ Inventario Actualizado: ${[Link]}`,
body: `Se ha actualizado el inventario con los siguientes datos:\n\nModelo: $
{[Link]}\nImpresora: ${[Link]}\nCantidad agregada: $
{[Link]}\nStock MÁXIMO: ${[Link] || 4}\n\n--\nSistema de
Gestión de Tintas`,
attachments: [pdf]
});
}

/******************************************
* FUNCIONES COMPARTIDAS *
******************************************/

function descontarDelInventario(items) {
try {
const hojaTintas = [Link]().getSheetByName("Tintas");
if (!hojaTintas) throw new Error("No se encontró la hoja 'Tintas'");

const datos = [Link](2, 1, [Link]()-1,


9).getValues();
let errores = [];

[Link](itemPedido => {
let encontrado = false;

for (let i = 0; i < [Link]; i++) {


const fila = datos[i];
const modeloInventario = `${fila[1]} - ${fila[4]} - ${fila[5]}`.trim();

if (modeloInventario === [Link] && fila[2] ===


[Link]) {
encontrado = true;
const stockActual = fila[7]; // Columna H (Existencia)

if (stockActual >= [Link]) {


// Descontar del inventario
[Link](i+2, 8).setValue(stockActual -
[Link]);

// Actualizar columna "Reponer" si es necesario


const stockMaximo = fila[6] || 4; // Columna G (Stock MAXIMO)
if ((stockActual - [Link]) < stockMaximo) {
[Link](i+2, 9).setValue("SI");
}
} else {
[Link](`Stock insuficiente: ${[Link]} ($
{[Link]}) - Disponible: ${stockActual}, Solicitado: $
{[Link]}`);
}
break;
}
}

if (!encontrado) {
[Link](`No encontrado en inventario: ${[Link]} ($
{[Link]})`);
}
});

if ([Link] > 0) {
return { success: false, message: [Link]('\n') };
}

return { success: true };


} catch (e) {
[Link]("Error en descontarDelInventario: " + [Link]());
return { success: false, message: "Error al descontar: " + [Link] };
}
}

function parsearDetalles(detalles) {
return [Link]("\n").map(linea => {
const match = [Link](/(.*) \((.*)\) x (\d+)/);
return match ? {
modelo: match[1].trim(),
impresora: match[2].trim(),
cantidad: parseInt(match[3])
} : null;
}).filter(item => item !== null);
}

function generarPDFDesdePlantilla(id, nombre, items, fecha, obs) {


try {
const doc = [Link](`Pedido ${id}`);
const body = [Link]();

// Logo
try {
const logoUrl = "[Link]
%20ANDRES%20BELLO%20CIR%[Link]";
const response = [Link](logoUrl);
const blob = [Link]();
[Link](blob)
.setWidth(100)
.setHeight(100)
.setAlignment([Link]);
} catch (e) {
[Link]("No se pudo cargar el logo: " + [Link]);
}

// Encabezado
[Link]("COLEGIO ANDRÉS BELLO - PAMPA")
.setHeading([Link].HEADING1)
.setAlignment([Link])
.setBold(true);

// Detalles
[Link](`\nFecha: ${[Link](fecha,
[Link](), "dd/MM/yyyy HH:mm")}`);
[Link](`Solicitante: ${nombre}`);
[Link]("\nSOLICITUD DE MATERIALES\
n").setHeading([Link].HEADING2);

// Cuerpo
[Link]("Por medio del presente, solicito los siguientes
materiales:\n");

// Tabla de items
const tabla = [Link]();
const header = [Link]();
["Modelo", "Cantidad", "Impresora"].forEach(text => {
[Link](text).setBackgroundColor("#dddddd").setBold(true);
});

[Link](i => {
const row = [Link]();
[Link]([Link]);
[Link]([Link]());
[Link]([Link]);
});

// Observaciones y firma
[Link](`\nObservaciones: ${obs || "Ninguna"}`).setItalic(true);
[Link]("\n\n\nAtentamente,\n\n_____________________________\n" +
nombre);
[Link]("\n\n\n\n\nAprobado por:\n\n_____________________________\
nNombre y firma")
.setSpacingBefore(150);

// Procesar documento
[Link]();
[Link](4000);

const pdf = [Link]("application/pdf");


[Link]([Link]()).setTrashed(true);
return pdf;
} catch (e) {
[Link]("Error en generarPDF: " + [Link]());
throw e;
}
}

/******************************************
* FUNCIONES DE STOCK CRÍTICO *
******************************************/

function verificarStockCritico() {
try {
const hoja = [Link]().getSheetByName("Tintas");
if (!hoja || [Link]() <= 1) return { success: false, message: "Hoja
Tintas no encontrada o vacía" };

const datos = [Link](2, 1, [Link]()-1, 9).getValues();


const itemsCriticos = datos
.filter(fila => fila[7] < (fila[6] || 4)) // Existencia < Stock MAXIMO
.map(fila => ({
modelo: `${fila[1]} - ${fila[4]} - ${fila[5]}`,
impresora: fila[2],
existencia: fila[7],
stockMaximo: fila[6] || 4,
ubicacion: fila[3]
}));

if ([Link] > 0) {
const resultado = enviarAlertaStockCritico(itemsCriticos);
return { success: true, count: [Link], alertaEnviada:
[Link] };
}

return { success: true, count: 0, message: "No hay items con stock crítico" };
} catch (e) {
[Link]("Error en verificarStockCritico: " + [Link]());
return { success: false, message: "Error: " + [Link] };
}
}

function enviarAlertaStockCritico(items) {
try {
const cuerpo = `
<h2>⚠️ Alerta de Stock Crítico</h2>
<p>Los siguientes items tienen existencia menor al stock máximo:</p>
<table border="1" cellpadding="5" style="border-collapse: collapse; width:
100%;">
<tr>
<th style="background-color: #f2f2f2;">Modelo</th>
<th style="background-color: #f2f2f2;">Impresora</th>
<th style="background-color: #f2f2f2;">Ubicación</th>
<th style="background-color: #f2f2f2;">Existencia</th>
<th style="background-color: #f2f2f2;">Stock Máximo</th>
</tr>
${[Link](item => `
<tr>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td style="color: ${[Link] < 2 ? 'red' : 'orange'}; font-
weight: bold;">${[Link]}</td>
<td>${[Link]}</td>
</tr>
`).join('')}
</table>
<p style="margin-top: 20px;">Favor reponer stock lo antes posible.</p>
<p>--<br/>Sistema Automático de Gestión de Tintas<br/>Colegio Andrés Bello -
Pampa</p>
`;

[Link]({
to: "cabpampa2016@[Link], coordimedia@[Link]",
subject: "⚠️ Alerta: Stock Crítico de Tintas",
htmlBody: cuerpo
});

return { success: true, count: [Link] };


} catch (e) {
[Link]("Error en enviarAlertaStockCritico: " + [Link]());
return { success: false, message: "Error al enviar alerta: " + [Link] };
}
}

/******************************************
* FUNCIONES DE PANEL DE CONTROL *
******************************************/

function mostrarPanelControl() {
const html = [Link]('PanelControl')
.setWidth(800)
.setHeight(650);
[Link]().showModalDialog(html, "Panel de Control de Tintas");
}

function getModelosDesdeInventario() {
try {
const hoja = [Link]().getSheetByName("Tintas");
if (!hoja || [Link]() <= 1) return [];

return [Link](2, 1, [Link]()-1, 9)


.getValues()
.filter(fila => fila[0])
.map(fila => ({
modelo: `${fila[1]} - ${fila[4]} - ${fila[5]}`.trim(),
impresora: fila[2],
existencia: fila[7]
}));
} catch (e) {
[Link]("Error en getModelosDesdeInventario: " + [Link]());
return [];
}
}

function obtenerStockCritico() {
try {
const hoja = [Link]().getSheetByName("Tintas");
if (!hoja || [Link]() <= 1) return [];

return [Link](2, 1, [Link]()-1, 9)


.getValues()
.filter(fila => fila[7] < (fila[6] || 4)) // Existencia < Stock MAXIMO
.map(fila => ({
modelo: `${fila[1]} - ${fila[4]} - ${fila[5]}`,
impresora: fila[2],
existencia: fila[7],
stockMaximo: fila[6] || 4,
ubicacion: fila[3],
reponer: fila[8]
}));
} catch (e) {
[Link]("Error en obtenerStockCritico: " + [Link]());
return [];
}
}

function enviarAlertaPersonalizada(destinatarios, mensajePersonalizado) {


try {
const itemsCriticos = obtenerStockCritico();

if ([Link] === 0) {
return { success: false, message: "No hay items con stock crítico
actualmente" };
}

const cuerpo = `
<h2>📢 Notificación Personalizada de Stock Crítico</h2>
<p>${mensajePersonalizado || 'Los siguientes items requieren atención:'}</p>
<table border="1" cellpadding="5" style="border-collapse: collapse; width:
100%;">
<tr>
<th style="background-color: #f2f2f2;">Modelo</th>
<th style="background-color: #f2f2f2;">Impresora</th>
<th style="background-color: #f2f2f2;">Ubicación</th>
<th style="background-color: #f2f2f2;">Existencia</th>
<th style="background-color: #f2f2f2;">Stock Máximo</th>
</tr>
${[Link](item => `
<tr>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td style="color: ${[Link] < 2 ? 'red' : 'orange'}; font-
weight: bold;">${[Link]}</td>
<td>${[Link]}</td>
</tr>
`).join('')}
</table>
<p style="margin-top: 20px;">--<br/>Sistema Automático de Gestión de
Tintas<br/>Colegio Andrés Bello - Pampa</p>
`;

[Link]({
to: destinatarios,
subject: "🔄 Notificación de Stock Crítico - Requiere Acción",
htmlBody: cuerpo
});

return { success: true, count: [Link] };


} catch (e) {
[Link]("Error en enviarAlertaPersonalizada: " + [Link]());
return { success: false, message: [Link] };
}
}
/******************************************
* FUNCIONES PARA LEER INVENTARIO *
******************************************/

function getModelosDesdeInventario() {
try {
const hoja = [Link]().getSheetByName("Tintas");
if (!hoja || [Link]() <= 1) return [];

const datos = [Link](2, 1, [Link]()-1, 9).getValues();


return [Link](fila => ({
marca: fila[1], // Columna B
impresora: fila[2], // Columna C
ubicacion: fila[3], // Columna D
numero: fila[4], // Columna E
color: fila[5], // Columna F
modeloCompleto: `${fila[1]} - ${fila[4]} - ${fila[5]}`, // Marca - Numero -
Color
existencia: fila[7] // Columna H
}));
} catch (e) {
[Link]("Error en getModelosDesdeInventario: " + [Link]());
return [];
}
}

/******************************************
* FUNCIONES PARA PROCESAR PEDIDOS - ACTUALIZADAS *
******************************************/

function parsearDetalles(detalles) {
// Ejemplo de formato: "Epson - 544 - Negro (L3250/L3150) x 1"
const regex = /^(.*?)\s*\((.*?)\)\s*x\s*(\d+)$/;
return [Link]("\n").map(linea => {
const match = [Link](regex);
if (match) {
return {
modelo: match[1].trim(), // "Epson - 544 - Negro"
impresora: match[2].trim(), // "L3250/L3150"
cantidad: parseInt(match[3]) // 1
};
}
return null;
}).filter(item => item !== null);
}

function descontarDelInventario(items) {
try {
const hojaTintas = [Link]().getSheetByName("Tintas");
if (!hojaTintas) throw new Error("No se encontró la hoja 'Tintas'");

const datos = [Link](2, 1, [Link]()-1,


9).getValues();
let errores = [];

[Link](itemPedido => {
let encontrado = false;

for (let i = 0; i < [Link]; i++) {


const fila = datos[i];
const modeloInventario = `${fila[1]} - ${fila[4]} - ${fila[5]}`.trim();

if (modeloInventario === [Link] && fila[2] ===


[Link]) {
encontrado = true;
const stockActual = fila[7]; // Columna H (Existencia)

if (stockActual >= [Link]) {


// Descontar del inventario
[Link](i+2, 8).setValue(stockActual -
[Link]);

// Actualizar columna "Reponer" si es necesario


const stockMaximo = fila[6] || 4; // Columna G (Stock MAXIMO)
if ((stockActual - [Link]) < stockMaximo) {
[Link](i+2, 9).setValue("SI");
}
} else {
[Link](`Stock insuficiente: ${[Link]} ($
{[Link]}) - Disponible: ${stockActual}, Solicitado: $
{[Link]}`);
}
break;
}
}

if (!encontrado) {
[Link](`No encontrado en inventario: ${[Link]} ($
{[Link]})`);
}
});

if ([Link] > 0) {
return { success: false, message: [Link]('\n') };
}

return { success: true };


} catch (e) {
[Link]("Error en descontarDelInventario: " + [Link]());
return { success: false, message: "Error al descontar: " + [Link] };
}
}

/******************************************
* FUNCIONES PARA FORMULARIO DE PEDIDOS - ACTUALIZADAS *
******************************************/

function getOpcionesInventario() {
const inventario = getModelosDesdeInventario();
return [Link](item => {
return {
modelo: [Link],
impresora: [Link],
ubicacion: [Link],
existencia: [Link],
displayText: `${[Link]} (${[Link]}) - ${[Link]}
- Stock: ${[Link]}`
};
});
}

También podría gustarte