Spaces:
Sleeping
Sleeping
File size: 10,442 Bytes
b6154b2 9218640 b6154b2 9218640 b6154b2 9218640 b6154b2 97c4d7a b6154b2 97c4d7a b6154b2 97c4d7a b6154b2 9218640 b6154b2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 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 | const SHEET_NAME = 'Productos';
const MOVEMENTS_SHEET_NAME = 'Movimientos';
const HEADERS = [
'ID',
'Producto',
'Precio',
'Cantidad',
'Unidad',
'FechaCaducidad',
'FechaIngreso',
'FechaProduccion',
'Categoria',
'CaducidadEstimada',
'Notas',
'Fuente',
'StockActual',
'ConsumidoTotal',
'CreadoEn',
'ActualizadoEn'
];
const MOVEMENT_HEADERS = [
'ID',
'ProductID',
'Producto',
'Tipo',
'Cantidad',
'Unidad',
'Notas',
'Fuente',
'CreadoEn'
];
function doGet(e) {
return handleRequest_({
method: 'GET',
params: e.parameter || {}
});
}
function doPost(e) {
const body = e.postData && e.postData.contents ? JSON.parse(e.postData.contents) : {};
return handleRequest_({
method: 'POST',
params: body
});
}
function handleRequest_(request) {
try {
const params = request.params || {};
validateToken_(params.token);
const action = params.action;
if (action === 'addRecord') return jsonResponse_(addRecord_(params.record || {}));
if (action === 'listRecords') return jsonResponse_(listRecords_(params.query || ''));
if (action === 'consumeProduct') return jsonResponse_(consumeProduct_(params.consumption || {}));
if (action === 'listMovements') return jsonResponse_(listMovements_());
if (action === 'replaceSnapshot') {
return jsonResponse_(replaceSnapshot_(params.records || [], params.movements || []));
}
return jsonResponse_({ ok: false, error: 'Accion no soportada.' });
} catch (error) {
return jsonResponse_({ ok: false, error: error.message });
}
}
function getSheet_() {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
let sheet = spreadsheet.getSheetByName(SHEET_NAME);
if (!sheet) sheet = spreadsheet.insertSheet(SHEET_NAME);
if (sheet.getLastRow() === 0) {
sheet.getRange(1, 1, 1, HEADERS.length).setValues([HEADERS]);
sheet.setFrozenRows(1);
}
return sheet;
}
function getMovementSheet_() {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
let sheet = spreadsheet.getSheetByName(MOVEMENTS_SHEET_NAME);
if (!sheet) sheet = spreadsheet.insertSheet(MOVEMENTS_SHEET_NAME);
if (sheet.getLastRow() === 0) {
sheet.getRange(1, 1, 1, MOVEMENT_HEADERS.length).setValues([MOVEMENT_HEADERS]);
sheet.setFrozenRows(1);
}
return sheet;
}
function validateToken_(token) {
const scriptToken = PropertiesService.getScriptProperties().getProperty('API_TOKEN');
if (!scriptToken) throw new Error('Falta API_TOKEN en Script Properties.');
if (token !== scriptToken) throw new Error('Token invalido.');
}
function addRecord_(record) {
const sheet = getSheet_();
const movementSheet = getMovementSheet_();
const createdAt = new Date().toISOString();
const id = record.id || Utilities.getUuid();
sheet.appendRow([
id,
record.producto || '',
Number(record.precio || 0),
Number(record.cantidad || 0),
record.unidad || 'unidad',
record.fechaCaducidad || '',
record.fechaIngreso || '',
record.fechaProduccion || '',
record.categoria || '',
String(Boolean(record.caducidadEstimada || false)),
record.notas || '',
record.fuente || 'web',
Number(record.stockActual != null ? record.stockActual : record.cantidad || 0),
Number(record.consumidoTotal || 0),
record.createdAt || createdAt,
record.updatedAt || createdAt
]);
movementSheet.appendRow([
Utilities.getUuid(),
id,
record.producto || '',
'ingreso',
Number(record.cantidad || 0),
record.unidad || 'unidad',
record.notas || '',
record.fuente || 'web',
createdAt
]);
return { ok: true, id: id, createdAt: createdAt };
}
function listRecords_(query) {
const sheet = getSheet_();
const values = sheet.getDataRange().getValues();
if (values.length <= 1) return { ok: true, records: [] };
const headers = values[0];
const rows = values.slice(1).map(function(row) {
return toRecord_(headers, row);
});
const normalizedQuery = String(query || '').toLowerCase().trim();
const records = normalizedQuery
? rows.filter(function(record) {
return JSON.stringify(record).toLowerCase().indexOf(normalizedQuery) >= 0;
})
: rows;
return { ok: true, records: records };
}
function toRecord_(headers, row) {
const result = {};
headers.forEach(function(header, index) {
result[header] = row[index];
});
return {
id: result.ID || '',
producto: result.Producto || '',
precio: result.Precio || 0,
cantidad: result.Cantidad || 0,
unidad: result.Unidad || 'unidad',
fechaCaducidad: formatDateValue_(result.FechaCaducidad),
fechaIngreso: formatDateValue_(result.FechaIngreso),
fechaProduccion: formatDateValue_(result.FechaProduccion),
categoria: result.Categoria || '',
caducidadEstimada: String(result.CaducidadEstimada).toLowerCase() === 'true',
notas: result.Notas || '',
fuente: result.Fuente || '',
stockActual: result.StockActual || 0,
consumidoTotal: result.ConsumidoTotal || 0,
createdAt: formatDateValue_(result.CreadoEn),
updatedAt: formatDateValue_(result.ActualizadoEn)
};
}
function consumeProduct_(consumption) {
const sheet = getSheet_();
const movementSheet = getMovementSheet_();
const values = sheet.getDataRange().getValues();
if (values.length <= 1) throw new Error('No hay productos registrados.');
const headers = values[0];
const rows = values.slice(1);
const targetProductId = consumption.productId || '';
let rowIndex = -1;
for (var i = 0; i < rows.length; i++) {
var currentRecord = toRecord_(headers, rows[i]);
if (targetProductId) {
if (currentRecord.id === targetProductId) {
rowIndex = i + 2;
break;
}
} else if (
String(currentRecord.producto).toLowerCase() === String(consumption.producto || '').toLowerCase() &&
Number(currentRecord.stockActual || 0) > 0
) {
rowIndex = i + 2;
break;
}
}
if (rowIndex === -1) throw new Error('No se encontro el producto para consumir.');
const recordValues = sheet.getRange(rowIndex, 1, 1, headers.length).getValues()[0];
const record = toRecord_(headers, recordValues);
const quantity = Number(consumption.cantidad || 0);
if (record.unidad !== consumption.unidad) throw new Error('La unidad no coincide.');
if (Number(record.stockActual) < quantity) throw new Error('Stock insuficiente en Google Sheets.');
const newStock = Number(record.stockActual) - quantity;
const newConsumed = Number(record.consumidoTotal || 0) + quantity;
const updatedAt = new Date().toISOString();
const columns = headerIndexMap_(headers);
sheet.getRange(rowIndex, columns.StockActual).setValue(newStock);
sheet.getRange(rowIndex, columns.ConsumidoTotal).setValue(newConsumed);
sheet.getRange(rowIndex, columns.ActualizadoEn).setValue(updatedAt);
movementSheet.appendRow([
Utilities.getUuid(),
record.id,
record.producto,
'consumo',
quantity,
record.unidad,
consumption.notas || '',
consumption.fuente || 'telegram-consumo',
updatedAt
]);
return {
ok: true,
id: record.id,
stockActual: newStock,
consumidoTotal: newConsumed,
updatedAt: updatedAt
};
}
function listMovements_() {
const sheet = getMovementSheet_();
const values = sheet.getDataRange().getValues();
if (values.length <= 1) return { ok: true, movements: [] };
const headers = values[0];
const movements = values.slice(1).map(function(row) {
const result = {};
headers.forEach(function(header, index) {
result[header] = row[index];
});
return {
id: result.ID || '',
productId: result.ProductID || '',
producto: result.Producto || '',
tipo: result.Tipo || '',
cantidad: result.Cantidad || 0,
unidad: result.Unidad || 'unidad',
notas: result.Notas || '',
fuente: result.Fuente || '',
createdAt: formatDateValue_(result.CreadoEn)
};
});
return { ok: true, movements: movements };
}
function replaceSnapshot_(records, movements) {
const productSheet = getSheet_();
const movementSheet = getMovementSheet_();
productSheet.clearContents();
movementSheet.clearContents();
productSheet.getRange(1, 1, 1, HEADERS.length).setValues([HEADERS]);
movementSheet.getRange(1, 1, 1, MOVEMENT_HEADERS.length).setValues([MOVEMENT_HEADERS]);
if (records.length) {
const productRows = records.map(function(record) {
return [
record.id || Utilities.getUuid(),
record.producto || '',
Number(record.precio || 0),
Number(record.cantidad || 0),
record.unidad || 'unidad',
record.fechaCaducidad || '',
record.fechaIngreso || '',
record.fechaProduccion || '',
record.categoria || '',
String(Boolean(record.caducidadEstimada || false)),
record.notas || '',
record.fuente || 'web',
Number(record.stockActual || 0),
Number(record.consumidoTotal || 0),
record.createdAt || '',
record.updatedAt || record.createdAt || ''
];
});
productSheet.getRange(2, 1, productRows.length, HEADERS.length).setValues(productRows);
}
if (movements.length) {
const movementRows = movements.map(function(movement) {
return [
movement.id || Utilities.getUuid(),
movement.productId || '',
movement.producto || '',
movement.tipo || '',
Number(movement.cantidad || 0),
movement.unidad || 'unidad',
movement.notas || '',
movement.fuente || '',
movement.createdAt || ''
];
});
movementSheet.getRange(2, 1, movementRows.length, MOVEMENT_HEADERS.length).setValues(movementRows);
}
productSheet.setFrozenRows(1);
movementSheet.setFrozenRows(1);
return { ok: true, records: records.length, movements: movements.length };
}
function headerIndexMap_(headers) {
const result = {};
headers.forEach(function(header, index) {
result[header] = index + 1;
});
return result;
}
function formatDateValue_(value) {
if (Object.prototype.toString.call(value) === '[object Date]' && !isNaN(value)) {
return Utilities.formatDate(value, Session.getScriptTimeZone(), 'yyyy-MM-dd');
}
return value || '';
}
function jsonResponse_(payload) {
return ContentService
.createTextOutput(JSON.stringify(payload))
.setMimeType(ContentService.MimeType.JSON);
}
|