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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Script para Google Sheets con visor 3D interactivo y gesti贸n de productos/pedidos
// Hojas: "Productos" y "Pedidos"

// Variables globales
var productosSheet = "Productos";
var pedidosSheet = "Pedidos";
var productosData = [];
var stlFiles = {};
var currentColor = "#000000";
var currentModel = null;

// Inicializar al abrir el documento
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('3D Viewer')
      .addItem('Agregar al carrito', 'addToCart')
      .addSeparator()
      .addItem('Limpiar carrito', 'clearCart')
      .addToUi();
  
  // Cargar datos de productos
  loadProducts();
  
  // Inicializar visor 3D
  init3DViewer();
}

// Cargar productos desde la hoja de c谩lculo
function loadProducts() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(productosSheet);
  if (!sheet) return;
  
  var data = sheet.getDataRange().getValues();
  productosData = [];
  
  for (var i = 1; i < data.length; i++) {
    if (data[i][0] && data[i][1]) {
      productosData.push({
        nombre: data[i][0],
        precio: data[i][1],
        vida: data[i][2],
        inventario: data[i][3],
        id: data[i][4]
      });
    }
  }
  
  Logger.log('Productos cargados: ' + productosData.length);
}

// Inicializar visor 3D
function init3DViewer() {
  // Crear HTML para el visor
  var html = HtmlService.createHtmlOutputFromFile('viewer')
      .setWidth(400)
      .setHeight(400);
      
  SpreadsheetApp.getUi().showModelessDialog(html, 'Visor 3D');
}

// Funci贸n para agregar al carrito
function addToCart(productName, quantity, client) {
  // Buscar el producto
  var product = productosData.find(p => 
    p.nombre.toLowerCase() === productName.toLowerCase()
  );
  
  if (!product) {
    SpreadsheetApp.getUi().alert('Producto no encontrado: ' + productName);
    return;
  }
  
  if (product.inventario <= 0) {
    SpreadsheetApp.getUi().alert('Producto sin inventario: ' + productName);
    return;
  }
  
  // Agregar a la hoja de pedidos
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(pedidosSheet);
  if (!sheet) {
    SpreadsheetApp.getUi().alert('Hoja de pedidos no encontrada');
    return;
  }
  
  sheet.appendRow([
    product.nombre,
    quantity,
    client,
    product.inventario,
    product.id
  ]);
  
  // Actualizar inventario
  updateInventory(product.nombre, -quantity);
  
  SpreadsheetApp.getUi().alert('Producto agregado al carrito: ' + product.nombre);
}

// Actualizar inventario
function updateInventory(productName, quantity) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(productosSheet);
  if (!sheet) return;
  
  var data = sheet.getDataRange().getValues();
  
  for (var i = 1; i < data.length; i++) {
    if (data[i][0] && data[i][0].toLowerCase() === productName.toLowerCase()) {
      var currentInv = parseInt(data[i][3]) || 0;
      var newInv = currentInv + quantity;
      sheet.getRange(i+1, 4).setValue(newInv);
      break;
    }
  }
}

// Limpiar carrito (eliminar 煤ltimas filas de pedidos)
function clearCart() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(pedidosSheet);
  if (!sheet) return;
  
  var lastRow = sheet.getLastRow();
  if (lastRow > 1) {
    sheet.deleteRows(2, lastRow - 1);
    SpreadsheetApp.getUi().alert('Carrito limpiado');
  }
}

// Cargar STL files (simulado - en producci贸n conectar铆a con Google Drive o base de datos)
function loadSTLFiles() {
  // Esta funci贸n simula la carga de archivos STL
  // En producci贸n, conectar铆a con Google Drive API o base de datos
  stlFiles = {
    'greca': 'data/stl/greca.stl',
    'minimalista': 'data/stl/minimalista.stl',
    'cl谩sico': 'data/stl/cl谩sico.stl',
    'moderno': 'data/stl/moderno.stl'
  };
  
  Logger.log('STL files cargados: ' + Object.keys(stlFiles).length);
}

// Cambiar color del modelo 3D
function changeColor(color) {
  currentColor = color;
  // Enviar mensaje al visor para actualizar color
  var app = UiApp.getActiveApplication();
  if (app) {
    app.getElementById('modelColor').setStyleAttribute('color', color);
  }
  
  SpreadsheetApp.getUi().showModelessDialog(
    HtmlService.createHtmlOutput(
      '<div id="modelColor" style="color:' + color + '">Color actualizado</div>'
    ).setWidth(200).setHeight(100),
    'Color'
  );
}

// Cargar modelo espec铆fico
function loadModel(modelName) {
  currentModel = modelName;
  // En producci贸n, cargar铆a el STL correspondiente
  Logger.log('Cargando modelo: ' + modelName);
}

// Funci贸n para el visor HTML (contenido del archivo viewer.html)
function getViewerHTML() {
  return `
    <!DOCTYPE html>
    <html>
    <head>
      <title>Visor 3D Interactivo</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
      <style>
        body {
          margin: 0;
          padding: 10px;
          background: #f0f0f0;
          font-family: Arial, sans-serif;
        }
        #viewer {
          width: 100%;
          height: 300px;
          border: 1px solid #ccc;
          background: #ffffff;
        }
        .color-picker {
          display: flex;
          gap: 5px;
          margin-top: 10px;
        }
        .color-btn {
          width: 30px;
          height: 30px;
          border: none;
          border-radius: 50%;
          cursor: pointer;
        }
      </style>
    </head>
    <body>
      <h3>Visor 3D - Selecciona un modelo</h3>
      <div id="viewer"></div>
      <div class="color-picker">
        <button class="color-btn" style="background: #000000" onclick="selectColor('#000000')"></button>
        <button class="color-btn" style="background: #ff0000" onclick="selectColor('#ff0000')"></button>
        <button class="color-btn" style="background: #00ff00" onclick="selectColor('#00ff00')"></button>
        <button class="color-btn" style="background: #0000ff" onclick="selectColor('#0000ff')"></button>
        <button class="color-btn" style="background: #ffff00" onclick="selectColor('#ffff00')"></button>
        <button class="color-btn" style="background: #ff00ff" onclick="selectColor('#ff00ff')"></button>
        <button class="color-btn" style="background: #00ffff" onclick="selectColor('#00ffff')"></button>
      </div>
      
      <script>
        let scene, camera, renderer, model;
        let currentColor = '#000000';
        
        function init() {
          scene = new THREE.Scene();
          camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
          camera.position.z = 5;
          
          renderer = new THREE.WebGLRenderer({ antialias: true });
          renderer.setSize(380, 280);
          document.getElementById('viewer').appendChild(renderer.domElement);
          
          // Crear grid
          const gridHelper = new THREE.GridHelper(10, 10);
          scene.add(gridHelper);
          
          animate();
        }
        
        function animate() {
          requestAnimationFrame(animate);
          if (model) {
            model.rotation.y += 0.01;
          }
          renderer.render(scene, camera);
        }
        
        function selectColor(color) {
          currentColor = color;
          if (model) {
            model.traverse((child) => {
              if (child.isMesh) {
                child.material.color.set(color);
              }
            });
          }
          google.script.run.withSuccessHandler(function() {}).changeColor(color);
        }
        
        function loadModel(modelName) {
          // Simular carga de modelo
          if (model) {
            scene.remove(model);
          }
          
          // Crear modelo simple para demostraci贸n
          const geometry = new THREE.BoxGeometry(2, 2, 2);
          const material = new THREE.MeshPhongMaterial({ 
            color: currentColor,
            shininess: 100
          });
          model = new THREE.Mesh(geometry, material);
          scene.add(model);
          
          // A帽adir luz
          const ambientLight = new THREE.AmbientLight(0x404040);
          scene.add(ambientLight);
          
          const pointLight = new THREE.PointLight(0xffffff, 1, 100);
          pointLight.position.set(10, 10, 10);
          scene.add(pointLight);
          
          google.script.run.withSuccessHandler(function() {}).loadModel(modelName);
        }
        
        // Inicializar al cargar
        window.onload = function() {
          init();
          // Cargar un modelo por defecto
          loadModel('greca');
        };
      </script>
    </body>
    </html>
  `;
}

// Funci贸n para obtener HTML del visor (llamada desde Google Sheets)
function showViewer() {
  var html = HtmlService.createHtmlOutput(getViewerHTML())
      .setWidth(420)
      .setHeight(450);
      
  SpreadsheetApp.getUi().showModelessDialog(html, 'Visor 3D');
}

// Manejar peticiones GET desde el formulario web
function doGet(e) {
  var action = e.parameter.action;
  
  if (action === 'products') {
    return getProducts();
  }
  
  if (action === 'order') {
    return saveOrder(e);
  }
  
  return ContentService.createTextOutput(JSON.stringify({ error: 'Acci贸n no vlida' }))
    .setMimeType(ContentService.MimeType.JSON);
}

// Obtener productos para el visor web
function getProducts() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(productosSheet);
  if (!sheet) {
    return ContentService.createTextOutput(JSON.stringify({ values: [] }))
      .setMimeType(ContentService.MimeType.JSON);
  }
  
  var data = sheet.getDataRange().getValues();
  var result = [];
  
  // Encabezados
  result.push(['id_producto', 'Productos', 'Precio_Unitario_con_costos', 'Precio unitario', 'vida promedio', 'INVENTARIO']);
  
  // Datos
  for (var i = 1; i < data.length; i++) {
    result.push([
      data[i][0], // id_producto
      data[i][1], // Productos
      data[i][2], // Precio_Unitario_con_costos
      data[i][3], // Precio unitario
      data[i][4], // vida promedio
      data[i][5]  // INVENTARIO
    ]);
  }
  
  return ContentService.createTextOutput(JSON.stringify({ values: result }))
    .setMimeType(ContentService.MimeType.JSON);
}

// Guardar pedido desde el formulario web
function saveOrder(e) {
  var product = e.parameter.product;
  var quantity = parseInt(e.parameter.quantity);
  var client = e.parameter.client;
  var address = e.parameter.address;
  var phone = e.parameter.phone;
  
  if (!product || !quantity || !client) {
    return ContentService.createTextOutput(JSON.stringify({ error: 'Faltan datos requeridos' }))
      .setMimeType(ContentService.MimeType.JSON);
  }
  
  try {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(pedidosSheet);
    if (!sheet) {
      return ContentService.createTextOutput(JSON.stringify({ error: 'Hoja de pedidos no encontrada' }))
        .setMimeType(ContentService.MimeType.JSON);
    }
    
    // Buscar el producto para obtener el ID
    var productosSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Productos');
    var productosData = productosSheet.getDataRange().getValues();
    var productId = '';
    var productPrice = 0;
    
    for (var i = 1; i < productosData.length; i++) {
      if (productosData[i][1] && productosData[i][1].toString().toLowerCase() === product.toLowerCase()) {
        productId = productosData[i][0];
        productPrice = productosData[i][2];
        break;
      }
    }
    
    // Generar ID de pedido
    var pedidoId = 'PED-' + new Date().getTime();
    
    // Agregar a la hoja de pedidos
    sheet.appendRow([
      product,          // Productos
      quantity,         // Cantidad
      client,           // Cliente
      '',               // INVENTARIO (dejar vaco)
      productId,       // id
      pedidoId,         // id_pedido
      productPrice * quantity, // Precio
      productId         // id_producto
    ]);
    
    // Actualizar inventario
    updateInventory(product, -quantity);
    
    return ContentService.createTextOutput(JSON.stringify({ 
      success: true, 
      pedidoId: pedidoId,
      total: productPrice * quantity
    }))
      .setMimeType(ContentService.MimeType.JSON);
    
  } catch (error) {
    return ContentService.createTextOutput(JSON.stringify({ error: error.toString() }))
      .setMimeType(ContentService.MimeType.JSON);
  }
}