UNPKG

n8n-nodes-tiny-erp-api-v2

Version:

Custom nodes for Tiny ERP integration with n8n, including AI tools for AI Agent workflows

183 lines 7.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.execute = exports.description = void 0; const n8n_workflow_1 = require("n8n-workflow"); const api_1 = require("../../transport/api"); exports.description = [ { displayName: 'Stock Updates Data', name: 'stockUpdatesData', type: 'json', default: '[]', description: 'Array of stock update objects to process in batch (max 20 updates per batch)', displayOptions: { show: { resource: ['products'], operation: ['updateStockBatch'], }, }, required: true, placeholder: `[ { "idProduto": "12345888", "quantidade": 10, "tipo": "E", "idDeposito": "123456" }, { "idProduto": "12345889", "quantidade": -5, "tipo": "S", "deposito": "deposito central" } ]`, }, { displayName: 'Batch Size', name: 'batchSize', type: 'number', default: 20, description: 'Number of stock updates to process per batch (max 20)', displayOptions: { show: { resource: ['products'], operation: ['updateStockBatch'], }, }, typeOptions: { minValue: 1, maxValue: 20, }, }, { displayName: 'Default Date', name: 'defaultDate', type: 'dateTime', default: '', description: 'Default date for stock movements (if not specified in individual updates)', displayOptions: { show: { resource: ['products'], operation: ['updateStockBatch'], }, }, placeholder: 'e.g., 2024-01-15 14:30:00', }, ]; async function execute(index) { const credentials = await this.getCredentials('tinyErpApi'); const api = new api_1.TinyErpApi(this, credentials); const stockUpdatesDataStr = this.getNodeParameter('stockUpdatesData', index); const batchSize = this.getNodeParameter('batchSize', index); const defaultDate = this.getNodeParameter('defaultDate', index); if (!stockUpdatesDataStr || stockUpdatesDataStr.trim() === '') { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Stock updates data is required for batch processing'); } let stockUpdatesData; try { stockUpdatesData = JSON.parse(stockUpdatesDataStr); } catch (error) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Invalid JSON in stock updates data: ${error.message}`); } if (!Array.isArray(stockUpdatesData)) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Stock updates data must be an array'); } if (stockUpdatesData.length === 0) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Stock updates data array cannot be empty'); } for (let i = 0; i < stockUpdatesData.length; i++) { const stockUpdate = stockUpdatesData[i]; if (!stockUpdate.idProduto) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Stock update at index ${i} is missing required field: idProduto`); } if (stockUpdate.quantidade === undefined || stockUpdate.quantidade === null) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Stock update at index ${i} is missing required field: quantidade`); } if (!stockUpdate.tipo || !['E', 'S', 'B'].includes(stockUpdate.tipo)) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Stock update at index ${i} has invalid or missing tipo (must be E, S, or B)`); } if (!stockUpdate.idDeposito && !stockUpdate.deposito) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Stock update at index ${i} must have either idDeposito or deposito`); } } try { const effectiveBatchSize = Math.min(batchSize, 20); const results = []; const batches = []; const defaultDateFormatted = defaultDate && defaultDate.trim() !== '' ? defaultDate.trim() : new Date().toISOString().replace('T', ' ').substring(0, 19); const processedUpdates = stockUpdatesData.map((stockUpdate) => { const processed = { idProduto: stockUpdate.idProduto.toString(), tipo: stockUpdate.tipo, quantidade: stockUpdate.quantidade.toString(), }; if (stockUpdate.idDeposito) { processed.idDeposito = stockUpdate.idDeposito.toString(); } else if (stockUpdate.deposito) { processed.deposito = stockUpdate.deposito.toString(); } if (stockUpdate.precoUnitario && stockUpdate.precoUnitario > 0) { processed.precoUnitario = stockUpdate.precoUnitario.toString(); } if (stockUpdate.data && stockUpdate.data.trim() !== '') { processed.data = stockUpdate.data.trim(); } else { processed.data = defaultDateFormatted; } if (stockUpdate.observacoes && stockUpdate.observacoes.trim() !== '') { processed.observacoes = stockUpdate.observacoes.trim(); } return processed; }); for (let i = 0; i < processedUpdates.length; i += effectiveBatchSize) { const batch = processedUpdates.slice(i, i + effectiveBatchSize); batches.push(batch); } console.log(`🔍 [Tiny ERP API] Processing ${processedUpdates.length} stock updates in ${batches.length} batches`); for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) { const batch = batches[batchIndex]; try { console.log(`🔍 [Tiny ERP API] Processing batch ${batchIndex + 1}/${batches.length} with ${batch.length} stock updates`); const batchResults = await api.updateStockBatch(batch); results.push(...(Array.isArray(batchResults) ? batchResults : [batchResults])); } catch (batchError) { console.error(`🔍 [Tiny ERP API] Batch ${batchIndex + 1} failed:`, batchError.message); results.push({ retorno: { status: 'Erro', erros: [{ erro: `Batch ${batchIndex + 1} failed: ${batchError.message}` }], batchIndex: batchIndex + 1, batchSize: batch.length, }, }); } } const responseData = { success: true, message: `Processed ${processedUpdates.length} stock updates in ${batches.length} batches`, operation: 'updateStockBatch', resource: 'products', totalUpdates: processedUpdates.length, totalBatches: batches.length, batchSize: effectiveBatchSize, timestamp: new Date().toISOString(), results: results, rateLimitInfo: api.getRateLimitInfo(), }; return [{ json: responseData }]; } catch (error) { if (error instanceof n8n_workflow_1.NodeOperationError) { throw error; } throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Failed to update stock in batch: ${error.message}`); } } exports.execute = execute; //# sourceMappingURL=updateStockBatch.operation.js.map