From a89d1e883a1f911568c861d8a3c7edb52943283c Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 26 Dec 2023 14:36:58 +0100 Subject: [PATCH 01/39] create rectification: refs #4466 --- db/changes/240201/00-invoiceRectification.sql | 21 ++++++ .../back/methods/invoice-in/clone.js | 71 ++++++++++++++----- .../back/methods/invoice-in/rectification.js | 58 +++++++++++++++ modules/invoiceIn/back/model-config.json | 3 + .../back/models/invoice-in-correction.json | 41 +++++++++++ modules/invoiceIn/back/models/invoice-in.js | 1 + 6 files changed, 176 insertions(+), 19 deletions(-) create mode 100644 db/changes/240201/00-invoiceRectification.sql create mode 100644 modules/invoiceIn/back/methods/invoice-in/rectification.js create mode 100644 modules/invoiceIn/back/models/invoice-in-correction.json diff --git a/db/changes/240201/00-invoiceRectification.sql b/db/changes/240201/00-invoiceRectification.sql new file mode 100644 index 000000000..4648a7eb2 --- /dev/null +++ b/db/changes/240201/00-invoiceRectification.sql @@ -0,0 +1,21 @@ +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('InvoiceIn', 'rectification', 'WRITE', 'ALLOW', 'ROLE', 'employee'); + +CREATE TABLE `vn`.`invoiceInCorrection` ( + `correctingFk` mediumint(8) UNSIGNED NOT NULL COMMENT 'Factura rectificativa', + `correctedFk` mediumint(8) UNSIGNED NOT NULL COMMENT 'Factura rectificada', + `cplusRectificationTypeFk` int(10) UNSIGNED NOT NULL, + `siiTypeInvoiceOutFk` int(10) UNSIGNED NOT NULL, + `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT 3, + PRIMARY KEY (`correctingFk`), + KEY `invoiceInCorrection_correctedFk` (`correctedFk`), + KEY `invoiceInCorrection_cplusRectificationTypeFk` (`cplusRectificationTypeFk`), + KEY `invoiceInCorrection_siiTypeInvoiceOut` (`siiTypeInvoiceOutFk`), + KEY `invoiceInCorrection_invoiceCorrectionTypeFk` (`invoiceCorrectionTypeFk`), + CONSTRAINT `invoiceInCorrection_correctedFk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_correctingFk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_siiTypeInvoiceOut` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_invoiceCorrectionTypeFk` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_cplusRectificationTypeFk` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE +); diff --git a/modules/invoiceIn/back/methods/invoice-in/clone.js b/modules/invoiceIn/back/methods/invoice-in/clone.js index 18df53a95..662ef52be 100644 --- a/modules/invoiceIn/back/methods/invoice-in/clone.js +++ b/modules/invoiceIn/back/methods/invoice-in/clone.js @@ -2,13 +2,17 @@ module.exports = Self => { Self.remoteMethodCtx('clone', { description: 'Clone the invoiceIn and as many invoiceInTax and invoiceInDueDay referencing it', accessType: 'WRITE', - accepts: { + accepts: [{ arg: 'id', type: 'number', required: true, description: 'The invoiceIn id', http: {source: 'path'} - }, + }, { + arg: 'isRectification', + type: 'boolean', + description: 'Clone quantities in negative and clone Intrastat' + }], returns: { type: 'object', root: true @@ -19,7 +23,7 @@ module.exports = Self => { } }); - Self.clone = async(ctx, id, options) => { + Self.clone = async(ctx, id, isRectification, options) => { const models = Self.app.models; let tx; const myOptions = {}; @@ -45,10 +49,22 @@ module.exports = Self => { 'isVatDeductible', 'withholdingSageFk', 'deductibleExpenseFk', - ] + ], + include: [ + { + relation: 'invoiceInTax', + }, + { + relation: 'invoiceInDueDay', + }, + { + relation: 'invoiceInIntrastat' + } + ], }, myOptions); - const sourceInvoiceInTax = await models.InvoiceInTax.find({where: {invoiceInFk: id}}, myOptions); - const sourceInvoiceInDueDay = await models.InvoiceInDueDay.find({where: {invoiceInFk: id}}, myOptions); + const invoiceInTax = sourceInvoiceIn.invoiceInTax(); + const invoiceInDueDay = sourceInvoiceIn.invoiceInDueDay(); + const invoiceInIntrastat = sourceInvoiceIn.invoiceInIntrastat(); const issued = new Date(sourceInvoiceIn.issued); issued.setMonth(issued.getMonth() + 1); @@ -68,30 +84,47 @@ module.exports = Self => { const promises = []; - for (let tax of sourceInvoiceInTax) { + for (let tax of invoiceInTax) { promises.push(models.InvoiceInTax.create({ invoiceInFk: clone.id, - taxableBase: tax.taxableBase, + taxableBase: isRectification ? -tax.taxableBase : tax.taxableBase, expenseFk: tax.expenseFk, - foreignValue: tax.foreignValue, + foreignValue: isRectification ? -tax.foreignValue : tax.foreignValue, taxTypeSageFk: tax.taxTypeSageFk, transactionTypeSageFk: tax.transactionTypeSageFk }, myOptions)); } - for (let dueDay of sourceInvoiceInDueDay) { - const dueDated = dueDay.dueDated; - dueDated.setMonth(dueDated.getMonth() + 1); + if (!isRectification) { + for (let dueDay of invoiceInDueDay) { + const dueDated = dueDay.dueDated; + dueDated.setMonth(dueDated.getMonth() + 1); - promises.push(models.InvoiceInDueDay.create({ - invoiceInFk: clone.id, - dueDated: dueDated, - bankFk: dueDay.bankFk, - amount: dueDay.amount, - foreignValue: dueDated.foreignValue, - }, myOptions)); + promises.push(models.InvoiceInDueDay.create({ + invoiceInFk: clone.id, + dueDated: dueDated, + bankFk: dueDay.bankFk, + amount: dueDay.amount, + foreignValue: dueDated.foreignValue, + }, myOptions)); + } } + if (isRectification) { + console.log(invoiceInIntrastat); + for (let intrastat of invoiceInIntrastat) { + promises.push(models.InvoiceInIntrastat.create({ + invoiceInFk: clone.id, + net: -intrastat.net, + intrastatFk: intrastat.intrastatFk, + amount: -intrastat.amount, + stems: -intrastat.stems, + country: intrastat.countryFk, + dated: Date.vnNew(), + statisticalValue: intrastat.statisticalValue + }, myOptions)); + } + } await Promise.all(promises); if (tx) await tx.commit(); diff --git a/modules/invoiceIn/back/methods/invoice-in/rectification.js b/modules/invoiceIn/back/methods/invoice-in/rectification.js new file mode 100644 index 000000000..95cac6d16 --- /dev/null +++ b/modules/invoiceIn/back/methods/invoice-in/rectification.js @@ -0,0 +1,58 @@ +module.exports = Self => { + Self.remoteMethodCtx('rectification', { + description: 'Creates a rectificated invoice in', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number' + }, { + arg: 'invoiceReason', + type: 'string', + }, { + arg: 'invoiceType', + type: 'string', + }, { + arg: 'invoiceClass', + type: 'string' + }], + returns: { + type: 'number', + root: true + }, + http: { + path: '/rectification', + verb: 'POST' + } + }); + + Self.rectification = async(ctx, id, invoiceReason, invoiceType, invoiceClass, options) => { + const models = Self.app.models; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const clone = await Self.clone(ctx, id, true, myOptions); + await models.InvoiceInCorrection.create({ + correctingFk: id, + correctedFk: clone.id, + cplusRectificationTypeFk: invoiceReason, + siiTypeInvoiceOutFk: invoiceClass, + invoiceCorrectionTypeFk: invoiceType + }, myOptions); + + if (tx) await tx.commit(); + return clone.id; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/invoiceIn/back/model-config.json b/modules/invoiceIn/back/model-config.json index bd37b3bf1..4e0adf7a3 100644 --- a/modules/invoiceIn/back/model-config.json +++ b/modules/invoiceIn/back/model-config.json @@ -5,6 +5,9 @@ "InvoiceInConfig": { "dataSource": "vn" }, + "InvoiceInCorrection": { + "dataSource": "vn" + }, "InvoiceInDueDay": { "dataSource": "vn" }, diff --git a/modules/invoiceIn/back/models/invoice-in-correction.json b/modules/invoiceIn/back/models/invoice-in-correction.json new file mode 100644 index 000000000..742812f7d --- /dev/null +++ b/modules/invoiceIn/back/models/invoice-in-correction.json @@ -0,0 +1,41 @@ +{ + "name": "InvoiceInCorrection", + "base": "VnModel", + "options": { + "mysql": { + "table": "invoiceInCorrection" + } + }, + "properties": { + "correctingFk": { + "id": true, + "type": "number" + }, + "correctedFk": { + "type": "number" + } + }, + "relations": { + "invoiceIn": { + "type": "belongsTo", + "model": "InvoiceIn", + "foreignKey": "correctingFk" + }, + "cplusRectificationType": { + "type": "belongsTo", + "model": "CplusRectificationType", + "foreignKey": "cplusRectificationTypeFk" + }, + "invoiceCorrectionType": { + "type": "belongsTo", + "model": "InvoiceCorrectionType", + "foreignKey": "invoiceCorrectionTypeFk" + }, + "siiTypeInvoiceOutFk": { + "type": "belongsTo", + "model": "SiiTypeInvoiceOut", + "foreignKey": "siiTypeInvoiceOutFk" + } + + } +} \ No newline at end of file diff --git a/modules/invoiceIn/back/models/invoice-in.js b/modules/invoiceIn/back/models/invoice-in.js index 82e0bf078..776ee720b 100644 --- a/modules/invoiceIn/back/models/invoice-in.js +++ b/modules/invoiceIn/back/models/invoice-in.js @@ -9,6 +9,7 @@ module.exports = Self => { require('../methods/invoice-in/invoiceInPdf')(Self); require('../methods/invoice-in/invoiceInEmail')(Self); require('../methods/invoice-in/getSerial')(Self); + require('../methods/invoice-in/rectification')(Self); Self.rewriteDbError(function(err) { if (err.code === 'ER_ROW_IS_REFERENCED_2' && err.sqlMessage.includes('vehicleInvoiceIn')) return new UserError(`This invoice has a linked vehicle.`); From 567879d64e4986c32ab5d3a38f8d4d6b4c13fe5d Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 28 Dec 2023 15:55:11 +0100 Subject: [PATCH 02/39] corrective back created: refs #4466 --- db/changes/240201/00-invoiceCorrective.sql | 260 ++++++++++++++++++ db/changes/240201/00-invoiceRectification.sql | 21 -- .../back/methods/invoice-in/clone.js | 5 +- .../{rectification.js => corrective.js} | 20 +- .../back/models/invoice-in-correction.json | 5 +- modules/invoiceIn/back/models/invoice-in.js | 3 +- modules/invoiceIn/back/models/invoice-in.json | 5 + .../back/models/sii-type-invoice-out.json | 3 + 8 files changed, 284 insertions(+), 38 deletions(-) create mode 100644 db/changes/240201/00-invoiceCorrective.sql delete mode 100644 db/changes/240201/00-invoiceRectification.sql rename modules/invoiceIn/back/methods/invoice-in/{rectification.js => corrective.js} (72%) diff --git a/db/changes/240201/00-invoiceCorrective.sql b/db/changes/240201/00-invoiceCorrective.sql new file mode 100644 index 000000000..68dfefb0a --- /dev/null +++ b/db/changes/240201/00-invoiceCorrective.sql @@ -0,0 +1,260 @@ +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('InvoiceIn', 'corrective', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceInCorrection', '*', '*', 'ALLOW', 'ROLE', 'administrative'); + +CREATE TABLE `vn`.`invoiceInCorrection` ( + `correctingFk` mediumint(8) UNSIGNED NOT NULL COMMENT 'Factura rectificativa', + `correctedFk` mediumint(8) UNSIGNED NOT NULL COMMENT 'Factura rectificada', + `cplusRectificationTypeFk` int(10) UNSIGNED NOT NULL, + `siiTypeInvoiceOutFk` int(10) UNSIGNED NOT NULL, + `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT 3, + PRIMARY KEY (`correctingFk`), + KEY `invoiceInCorrection_correctedFk` (`correctedFk`), + KEY `invoiceInCorrection_cplusRectificationTypeFk` (`cplusRectificationTypeFk`), + KEY `invoiceInCorrection_siiTypeInvoiceOut` (`siiTypeInvoiceOutFk`), + KEY `invoiceInCorrection_invoiceCorrectionTypeFk` (`invoiceCorrectionTypeFk`), + CONSTRAINT `invoiceInCorrection_correctedFk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_correctingFk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_siiTypeInvoiceOut` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_invoiceCorrectionTypeFk` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_cplusRectificationTypeFk` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE +); + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `sage`.`invoiceIn_add`(vInvoiceInFk INT, vXDiarioFk INT) +BEGIN +/** + * Traslada la info de contabilidad relacionada con las facturas recibidas + * + * @vInvoiceInFk Factura recibida + * @vXDiarioFk Id tabla XDiario + */ + DECLARE vInvoiceInOriginalFk INT; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vBase DOUBLE; + DECLARE vVat DOUBLE; + DECLARE vRate DOUBLE; + DECLARE vTransactionCode INT; + DECLARE vCounter INT DEFAULT 0; + DECLARE vTransactionCodeOld INT; + DECLARE vTaxCode INT; + DECLARE vTaxCodeOld INT; + DECLARE vOperationCode VARCHAR(1); + DECLARE vIsIntracommunity BOOL DEFAULT FALSE; + DECLARE vSerialDua VARCHAR(1) DEFAULT 'D'; + DECLARE vInvoiceTypeReceived VARCHAR(1); + DECLARE vInvoiceTypeInformative VARCHAR(1); + DECLARE vIsInformativeExportation BOOL DEFAULT FALSE; + + DECLARE vCursor CURSOR FOR + SELECT it.taxableBase, + CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)), + t.PorcentajeIva, + it.transactionTypeSageFk, + it.taxTypeSageFk, + tty.isIntracommunity, + tt.ClaveOperacionDefecto + FROM vn.invoiceIn i + JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id + JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk + JOIN taxType tty ON tty.id = t.CodigoIva + JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk + LEFT JOIN vn.dua d ON d.id = vInvoiceInFk + WHERE i.id = vInvoiceInFk + AND d.id IS NULL; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DELETE FROM movContaIVA + WHERE id = vXDiarioFk; + + SELECT codeSage INTO vInvoiceTypeReceived + FROM invoiceType WHERE code ='received'; + + SELECT codeSage INTO vInvoiceTypeInformative + FROM invoiceType WHERE code ='informative'; + + INSERT INTO movContaIVA(id, LibreA1) + VALUES (vXDiarioFk, vInvoiceInFk); + + OPEN vCursor; + + l: LOOP + FETCH vCursor INTO vBase, + vVat, + vRate, + vTransactionCode, + vTaxCode, + vIsIntracommunity, + vOperationCode; + + IF vDone THEN + LEAVE l; + END IF; + + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; + + IF vOperationCode IS NOT NULL THEN + UPDATE movContaIVA + SET ClaveOperacionFactura = vOperationCode + WHERE id = vXDiarioFk; + END IF; + + SET vCounter = vCounter + 1; + CASE vCounter + WHEN 1 THEN + UPDATE movContaIVA + SET BaseIva1 = vBase, + PorIva1 = vRate, + CuotaIva1 = vVat, + CodigoTransaccion1 = vTransactionCode, + CodigoIva1 = vTaxCode + WHERE id = vXDiarioFk; + + WHEN 2 THEN + UPDATE movContaIVA + SET BaseIva2 = vBase, + PorIva2 = vRate, + CuotaIva2 = vVat, + CodigoTransaccion2 = vTransactionCode, + CodigoIva2 = vTaxCode + WHERE id = vXDiarioFk; + WHEN 3 THEN + UPDATE movContaIVA + SET BaseIva3 = vBase, + PorIva3 = vRate, + CuotaIva3 = vVat, + CodigoTransaccion3 = vTransactionCode, + CodigoIva3 = vTaxCode + WHERE id = vXDiarioFk; + WHEN 4 THEN + UPDATE movContaIVA + SET BaseIva4 = vBase, + PorIva4 = vRate, + CuotaIva4 = vVat, + CodigoTransaccion4 = vTransactionCode, + CodigoIva4 = vTaxCode + WHERE id = vXDiarioFk; + ELSE + SELECT vXDiarioFk INTO vXDiarioFk; + END CASE; + + IF vIsIntracommunity THEN + UPDATE movContaIVA + SET Intracomunitaria = TRUE + WHERE id = vXDiarioFk; + END IF; + + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; + + END LOOP; + + CLOSE vCursor; + + SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation + FROM vn.dua d + LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN + AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci + WHERE d.ASIEN = ( + SELECT ASIEN + FROM vn.XDiario + WHERE id = vXDiarioFk) + LIMIT 1; + + UPDATE movContaIVA mci + JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk + JOIN vn.XDiario x ON x.id = mci.id + LEFT JOIN tmp.invoiceDua id ON id.id = mci.id + JOIN vn.supplier s ON s.id = ii.supplierFk + JOIN Naciones n ON n.countryFk = s.countryFk + SET mci.CodigoDivisa = ii.currencyFk, + mci.Año = YEAR(ii.issued), + mci.Serie = ii.serial, + mci.Factura = ii.id, + mci.FechaFactura = ii.issued, + mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + + IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + + IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + + IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0), + mci.TipoFactura = IF(id.id, + IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), + IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)), + mci.CodigoCuentaFactura = x.SUBCTA, + mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif), + mci.Nombre = s.name, + mci.SiglaNacion = n.SiglaNacion, + mci.EjercicioFactura = YEAR(ii.issued), + mci.FechaOperacion = ii.issued, + mci.MantenerAsiento = TRUE, + mci.SuFacturaNo = ii.supplierRef, + mci.IvaDeducible1 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva1, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + mci.IvaDeducible2 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva2, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + mci.IvaDeducible3 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva3, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + mci.IvaDeducible4 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva4, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + mci.FechaFacturaOriginal = x.FECHA_EX + WHERE mci.id = vXDiarioFk; + + -- RETENCIONES + UPDATE movContaIVA mci + JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk + JOIN vn.XDiario x ON x.id = mci.id + JOIN vn.supplier s ON s.id = supplierFk + JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id + JOIN vn.expense e ON e.id = iit.expenseFk + JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk + LEFT JOIN tmp.invoiceDua id ON id.id = mci.id + JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase + FROM vn.XDiario x1 + JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN + WHERE x2.BASEEURO <> 0 + AND x1.id = vXDiarioFk + )sub + JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio' + SET mci.CodigoRetencion = t.CodigoRetencion, + mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura), + mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase), + mci.PorRetencion = t.PorcentajeRetencion, + mci.ImporteRetencion = iit.taxableBase * - 1 + WHERE mci.id = vXDiarioFk + AND e.name = 'Retenciones' + AND id.id IS NULL; + + -- SAGE + SELECT correctedFk INTO vInvoiceInOriginalFk + FROM vn.invoiceInCorrection + WHERE correctingFk = vInvoiceInFk; + + IF vInvoiceInOriginalFk THEN + + UPDATE movContaIVA mci + JOIN vn.invoiceInRefund iir ON iir.invoiceInRefundFk = vInvoiceInFk + JOIN (SELECT issued, + SUM(sub.taxableBase) taxableBase, + SUM(ROUND((sub.taxableBase * sub.PorcentajeIva) / 100 , 2)) vat + FROM(SELECT issued, + SUM(iit.taxableBase) taxableBase, + ti.PorcentajeIva + FROM vn.invoiceIn i + JOIN vn.invoiceInTax iit ON iit.invoiceInFk = i.id + JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk + WHERE i.id = vInvoiceInOriginalFk + GROUP BY ti.CodigoIva)sub + )invoiceInOriginal + JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa' + SET mci.TipoRectificativa = iir.refundCategoryFk, + mci.ClaseAbonoRectificativas = iir.refundType, + mci.FechaFacturaOriginal = invoiceInOriginal.issued, + mci.FechaOperacion = invoiceInOriginal.issued, + mci.BaseImponibleOriginal = invoiceInOriginal.taxableBase, + mci.CuotaIvaOriginal = invoiceInOriginal.vat, + mci.ClaveOperacionFactura = co.ClaveOperacionFactura_ + WHERE mci.id = vXDiarioFk; + + END IF; + + +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/changes/240201/00-invoiceRectification.sql b/db/changes/240201/00-invoiceRectification.sql deleted file mode 100644 index 4648a7eb2..000000000 --- a/db/changes/240201/00-invoiceRectification.sql +++ /dev/null @@ -1,21 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('InvoiceIn', 'rectification', 'WRITE', 'ALLOW', 'ROLE', 'employee'); - -CREATE TABLE `vn`.`invoiceInCorrection` ( - `correctingFk` mediumint(8) UNSIGNED NOT NULL COMMENT 'Factura rectificativa', - `correctedFk` mediumint(8) UNSIGNED NOT NULL COMMENT 'Factura rectificada', - `cplusRectificationTypeFk` int(10) UNSIGNED NOT NULL, - `siiTypeInvoiceOutFk` int(10) UNSIGNED NOT NULL, - `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT 3, - PRIMARY KEY (`correctingFk`), - KEY `invoiceInCorrection_correctedFk` (`correctedFk`), - KEY `invoiceInCorrection_cplusRectificationTypeFk` (`cplusRectificationTypeFk`), - KEY `invoiceInCorrection_siiTypeInvoiceOut` (`siiTypeInvoiceOutFk`), - KEY `invoiceInCorrection_invoiceCorrectionTypeFk` (`invoiceCorrectionTypeFk`), - CONSTRAINT `invoiceInCorrection_correctedFk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `invoiceInCorrection_correctingFk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `invoiceInCorrection_siiTypeInvoiceOut` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE, - CONSTRAINT `invoiceInCorrection_invoiceCorrectionTypeFk` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE, - CONSTRAINT `invoiceInCorrection_cplusRectificationTypeFk` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE -); diff --git a/modules/invoiceIn/back/methods/invoice-in/clone.js b/modules/invoiceIn/back/methods/invoice-in/clone.js index 662ef52be..ce1ec178d 100644 --- a/modules/invoiceIn/back/methods/invoice-in/clone.js +++ b/modules/invoiceIn/back/methods/invoice-in/clone.js @@ -68,7 +68,9 @@ module.exports = Self => { const issued = new Date(sourceInvoiceIn.issued); issued.setMonth(issued.getMonth() + 1); - const clonedRef = sourceInvoiceIn.supplierRef + '(2)'; + const totalCorrections = await models.InvoiceInCorrection.count({correctedFk: id}, myOptions); + + const clonedRef = sourceInvoiceIn.supplierRef + `(${totalCorrections + 2})`; const clone = await models.InvoiceIn.create({ serial: sourceInvoiceIn.serial, @@ -111,7 +113,6 @@ module.exports = Self => { } if (isRectification) { - console.log(invoiceInIntrastat); for (let intrastat of invoiceInIntrastat) { promises.push(models.InvoiceInIntrastat.create({ invoiceInFk: clone.id, diff --git a/modules/invoiceIn/back/methods/invoice-in/rectification.js b/modules/invoiceIn/back/methods/invoice-in/corrective.js similarity index 72% rename from modules/invoiceIn/back/methods/invoice-in/rectification.js rename to modules/invoiceIn/back/methods/invoice-in/corrective.js index 95cac6d16..05f632bcd 100644 --- a/modules/invoiceIn/back/methods/invoice-in/rectification.js +++ b/modules/invoiceIn/back/methods/invoice-in/corrective.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('rectification', { + Self.remoteMethodCtx('corrective', { description: 'Creates a rectificated invoice in', accessType: 'WRITE', accepts: [{ @@ -7,25 +7,25 @@ module.exports = Self => { type: 'number' }, { arg: 'invoiceReason', - type: 'string', + type: 'number', }, { arg: 'invoiceType', - type: 'string', + type: 'number', }, { arg: 'invoiceClass', - type: 'string' + type: 'number' }], returns: { type: 'number', root: true }, http: { - path: '/rectification', + path: '/corrective', verb: 'POST' } }); - Self.rectification = async(ctx, id, invoiceReason, invoiceType, invoiceClass, options) => { + Self.corrective = async(ctx, id, invoiceReason, invoiceType, invoiceClass, options) => { const models = Self.app.models; const myOptions = {}; let tx; @@ -41,11 +41,11 @@ module.exports = Self => { try { const clone = await Self.clone(ctx, id, true, myOptions); await models.InvoiceInCorrection.create({ - correctingFk: id, - correctedFk: clone.id, - cplusRectificationTypeFk: invoiceReason, + correctingFk: clone.id, + correctedFk: id, + cplusRectificationTypeFk: invoiceType, siiTypeInvoiceOutFk: invoiceClass, - invoiceCorrectionTypeFk: invoiceType + invoiceCorrectionTypeFk: invoiceReason }, myOptions); if (tx) await tx.commit(); diff --git a/modules/invoiceIn/back/models/invoice-in-correction.json b/modules/invoiceIn/back/models/invoice-in-correction.json index 742812f7d..e94bb9ed8 100644 --- a/modules/invoiceIn/back/models/invoice-in-correction.json +++ b/modules/invoiceIn/back/models/invoice-in-correction.json @@ -10,16 +10,13 @@ "correctingFk": { "id": true, "type": "number" - }, - "correctedFk": { - "type": "number" } }, "relations": { "invoiceIn": { "type": "belongsTo", "model": "InvoiceIn", - "foreignKey": "correctingFk" + "foreignKey": "correctedFk" }, "cplusRectificationType": { "type": "belongsTo", diff --git a/modules/invoiceIn/back/models/invoice-in.js b/modules/invoiceIn/back/models/invoice-in.js index 776ee720b..af5efbcdf 100644 --- a/modules/invoiceIn/back/models/invoice-in.js +++ b/modules/invoiceIn/back/models/invoice-in.js @@ -9,7 +9,8 @@ module.exports = Self => { require('../methods/invoice-in/invoiceInPdf')(Self); require('../methods/invoice-in/invoiceInEmail')(Self); require('../methods/invoice-in/getSerial')(Self); - require('../methods/invoice-in/rectification')(Self); + require('../methods/invoice-in/corrective')(Self); + Self.rewriteDbError(function(err) { if (err.code === 'ER_ROW_IS_REFERENCED_2' && err.sqlMessage.includes('vehicleInvoiceIn')) return new UserError(`This invoice has a linked vehicle.`); diff --git a/modules/invoiceIn/back/models/invoice-in.json b/modules/invoiceIn/back/models/invoice-in.json index 5be55c851..f00f50ecd 100644 --- a/modules/invoiceIn/back/models/invoice-in.json +++ b/modules/invoiceIn/back/models/invoice-in.json @@ -100,6 +100,11 @@ "type": "belongsTo", "model": "Dms", "foreignKey": "dmsFk" + }, + "invoiceInCorrection": { + "type": "hasOne", + "model": "InvoiceInCorrection", + "foreignKey": "correctedFk" } } } diff --git a/modules/invoiceOut/back/models/sii-type-invoice-out.json b/modules/invoiceOut/back/models/sii-type-invoice-out.json index 17b312617..24e90a8d5 100644 --- a/modules/invoiceOut/back/models/sii-type-invoice-out.json +++ b/modules/invoiceOut/back/models/sii-type-invoice-out.json @@ -14,6 +14,9 @@ }, "description": { "type": "string" + }, + "code": { + "type": "string" } } } From e33861a80d1da65ba34ef8dac31f77eb519411e0 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 26 Jan 2024 12:15:53 +0100 Subject: [PATCH 03/39] fix: refs #6703 filter --- .../00-invoiceCorrective.sql | 0 .../back/methods/invoice-in/filter.js | 18 +++++++++++++++++- .../back/models/invoice-in-correction.json | 2 +- 3 files changed, 18 insertions(+), 2 deletions(-) rename db/changes/{240201 => 240601}/00-invoiceCorrective.sql (100%) diff --git a/db/changes/240201/00-invoiceCorrective.sql b/db/changes/240601/00-invoiceCorrective.sql similarity index 100% rename from db/changes/240201/00-invoiceCorrective.sql rename to db/changes/240601/00-invoiceCorrective.sql diff --git a/modules/invoiceIn/back/methods/invoice-in/filter.js b/modules/invoiceIn/back/methods/invoice-in/filter.js index e9d3da43c..9a4495372 100644 --- a/modules/invoiceIn/back/methods/invoice-in/filter.js +++ b/modules/invoiceIn/back/methods/invoice-in/filter.js @@ -1,4 +1,3 @@ - const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; const buildFilter = require('vn-loopback/util/filter').buildFilter; const mergeFilters = require('vn-loopback/util/filter').mergeFilters; @@ -80,6 +79,11 @@ module.exports = Self => { type: 'boolean', description: 'Whether the invoice is booked or not', }, + { + arg: 'correctedFk', + type: 'number', + description: 'The corrected invoice', + } ], returns: { type: ['object'], @@ -93,6 +97,7 @@ module.exports = Self => { Self.filter = async(ctx, filter, options) => { const conn = Self.dataSource.connector; + const models = Self.app.models; const args = ctx.args; const myOptions = {}; @@ -105,6 +110,14 @@ module.exports = Self => { dateTo.setHours(23, 59, 0, 0); } + let correctings; + if (args.correctedFk) { + correctings = await models.InvoiceInCorrection.find({ + fields: ['correctingFk'], + where: {correctedFk: args.correctedFk} + }); + } + const where = buildFilter(ctx.args, (param, value) => { switch (param) { case 'search': @@ -128,6 +141,8 @@ module.exports = Self => { return {[`ii.${param}`]: value}; case 'awbCode': return {'sub.code': value}; + case 'correctedFk': + return {'ii.id': {inq: correctings.map(x => x.correctingFk)}}; } }); @@ -186,6 +201,7 @@ module.exports = Self => { const itemsIndex = stmts.push(stmt) - 1; const sql = ParameterizedSQL.join(stmts, ';'); + console.log(sql); const result = await conn.executeStmt(sql, myOptions); return itemsIndex === 0 ? result : result[itemsIndex]; diff --git a/modules/invoiceIn/back/models/invoice-in-correction.json b/modules/invoiceIn/back/models/invoice-in-correction.json index e94bb9ed8..52e16d420 100644 --- a/modules/invoiceIn/back/models/invoice-in-correction.json +++ b/modules/invoiceIn/back/models/invoice-in-correction.json @@ -28,7 +28,7 @@ "model": "InvoiceCorrectionType", "foreignKey": "invoiceCorrectionTypeFk" }, - "siiTypeInvoiceOutFk": { + "siiTypeInvoiceOut": { "type": "belongsTo", "model": "SiiTypeInvoiceOut", "foreignKey": "siiTypeInvoiceOutFk" From ab3fdf4fe4078d68f05e44eb92cb54b33a672a80 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 26 Jan 2024 12:33:04 +0100 Subject: [PATCH 04/39] fix: refs #6703 remove console log --- modules/invoiceIn/back/methods/invoice-in/filter.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/invoiceIn/back/methods/invoice-in/filter.js b/modules/invoiceIn/back/methods/invoice-in/filter.js index 9a4495372..0d3b5f14a 100644 --- a/modules/invoiceIn/back/methods/invoice-in/filter.js +++ b/modules/invoiceIn/back/methods/invoice-in/filter.js @@ -201,7 +201,6 @@ module.exports = Self => { const itemsIndex = stmts.push(stmt) - 1; const sql = ParameterizedSQL.join(stmts, ';'); - console.log(sql); const result = await conn.executeStmt(sql, myOptions); return itemsIndex === 0 ? result : result[itemsIndex]; From ed0f942a5780ee083036642290d2e2bb0b1bed67 Mon Sep 17 00:00:00 2001 From: ivanm Date: Tue, 30 Jan 2024 09:45:37 +0100 Subject: [PATCH 05/39] refs #6444 create vn.intrastat_estimateNet.sql --- .../vn/functions/intrastat_estimateNet.sql | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 db/routines/vn/functions/intrastat_estimateNet.sql diff --git a/db/routines/vn/functions/intrastat_estimateNet.sql b/db/routines/vn/functions/intrastat_estimateNet.sql new file mode 100644 index 000000000..4d66e30de --- /dev/null +++ b/db/routines/vn/functions/intrastat_estimateNet.sql @@ -0,0 +1,19 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`intrastat_estimateNet`(intINSTRASTAT INTEGER,intUNIDADES INTEGER) + RETURNS double + DETERMINISTIC +BEGIN + + DECLARE n DOUBLE; + + SELECT ROUND(intUNIDADES / (SUM(MEDIA) / COUNT(media)), 2) INTO n FROM + (SELECT *, unidades / neto MEDIA + FROM vn2008.intrastat_data + WHERE intrastat_id = intINSTRASTAT AND neto + AND unidades > 0 + ORDER BY odbc_date DESC + LIMIT 20) t; + RETURN n/2; + +END$$ +DELIMITER ; \ No newline at end of file From da2a2b5f09cb85d4f01da06265db356fe96780dd Mon Sep 17 00:00:00 2001 From: ivanm Date: Tue, 30 Jan 2024 13:33:54 +0100 Subject: [PATCH 06/39] refs #6444 Remove vn2008.intrastat_neto function --- .../vn2008/functions/intrastat_neto.sql | 20 ------------------- 1 file changed, 20 deletions(-) delete mode 100644 db/routines/vn2008/functions/intrastat_neto.sql diff --git a/db/routines/vn2008/functions/intrastat_neto.sql b/db/routines/vn2008/functions/intrastat_neto.sql deleted file mode 100644 index 34e01de8c..000000000 --- a/db/routines/vn2008/functions/intrastat_neto.sql +++ /dev/null @@ -1,20 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn2008`.`intrastat_neto`(intINSTRASTAT INTEGER,intUNIDADES INTEGER) - RETURNS double - DETERMINISTIC -BEGIN - - DECLARE n DOUBLE; - - SELECT ROUND(intUNIDADES / (SUM(MEDIA) / COUNT(media)), 2) INTO n FROM - (SELECT *, unidades / neto MEDIA - FROM intrastat_data - WHERE intrastat_id = intINSTRASTAT AND neto - AND unidades > 0 - ORDER BY odbc_date DESC - LIMIT 20) t; - -- JGF 01/06 per a evitar Kg en negatiu - RETURN n/2; - -END$$ -DELIMITER ; From aba0d971063386e646dfc36ea8d915d5210503a8 Mon Sep 17 00:00:00 2001 From: Jbreso Date: Wed, 31 Jan 2024 09:00:43 +0100 Subject: [PATCH 07/39] feat: refs#5167 Update --- db/routines/vn/procedures/fustControl.sql | 79 ------------------- .../vn/procedures/fustControlDetail.sql | 36 --------- 2 files changed, 115 deletions(-) delete mode 100644 db/routines/vn/procedures/fustControl.sql delete mode 100644 db/routines/vn/procedures/fustControlDetail.sql diff --git a/db/routines/vn/procedures/fustControl.sql b/db/routines/vn/procedures/fustControl.sql deleted file mode 100644 index 506354b20..000000000 --- a/db/routines/vn/procedures/fustControl.sql +++ /dev/null @@ -1,79 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`fustControl`(vFromDated DATE, vToDated DATE) -BEGIN - - DECLARE vSijsnerClientFk INT DEFAULT 19752; - - DECLARE vDateStart DATETIME; - DECLARE vDateEnd DATETIME; - - SET vDateStart = vFromDated; - SET vDateEnd = util.Dayend(vToDated); - - SELECT p.id FustCode, - CAST(sent.stucks AS DECIMAL(10,0)) FH, - CAST(tp.stucks AS DECIMAL(10,0)) Tickets, - CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, - CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo - FROM vn.packaging p - LEFT JOIN ( - SELECT FustCode, sum(fustQuantity) stucks - FROM ( - SELECT IFNULL(pe.equivalentFk ,b.packagingFk) FustCode, s.quantity / b.packing AS fustQuantity - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk - JOIN vn.buy b ON b.id = lb.buy_id - JOIN vn.packaging p ON p.id = b.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk - WHERE t.shipped BETWEEN vDateStart AND vDateEnd - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA') sub - GROUP BY FustCode) sent ON sent.FustCode = p.id - LEFT JOIN ( - SELECT FustCode, sum(quantity) stucks - FROM ( - SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk - WHERE t.shipped BETWEEN vDateStart AND vDateEnd - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA' - AND t.clientFk != vSijsnerClientFk - AND tp.quantity > 0) sub - GROUP BY FustCode) tp ON tp.FustCode = p.id - LEFT JOIN ( - SELECT FustCode, sum(quantity) stucks - FROM ( - SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND t.clientFk = vSijsnerClientFk) sub - GROUP BY FustCode) sj ON sj.FustCode = p.id - WHERE sent.stucks - OR tp.stucks - OR sj.stucks; - -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/fustControlDetail.sql b/db/routines/vn/procedures/fustControlDetail.sql deleted file mode 100644 index a48a3531b..000000000 --- a/db/routines/vn/procedures/fustControlDetail.sql +++ /dev/null @@ -1,36 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`fustControlDetail`(vFromDated DATE, vToDated DATE) -BEGIN - - DECLARE vSijsnerClientFk INT DEFAULT 19752; - - DECLARE vDateStart DATETIME; - DECLARE vDateEnd DATETIME; - - SET vDateStart = vFromDated; - SET vDateEnd = util.Dayend(vToDated); - - SELECT a.nickname shopName, - a.city , - IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, - tp.quantity, - tp.ticketFk, - CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk - WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated) - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA' - AND t.clientFk != vSijsnerClientFk - AND tp.quantity > 0; - -END$$ -DELIMITER ; From a5e5a0d45dd476201268328b550ddb706000ec5c Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 31 Jan 2024 09:03:08 +0100 Subject: [PATCH 08/39] feat: #6749 se mira la vida para buscar dias en el pasado --- .../cache/procedures/available_refresh.sql | 54 +++++++++---------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/db/routines/cache/procedures/available_refresh.sql b/db/routines/cache/procedures/available_refresh.sql index cae0458ff..d0939e568 100644 --- a/db/routines/cache/procedures/available_refresh.sql +++ b/db/routines/cache/procedures/available_refresh.sql @@ -5,7 +5,8 @@ proc: BEGIN DECLARE vReserveDate DATETIME; DECLARE vParams CHAR(100); DECLARE vInventoryDate DATE; - DECLARE vIsLogifloraDay BOOLEAN; + DECLARE vLifeScope DATE; + DECLARE vWarehouseFkInventory INT; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN @@ -26,43 +27,42 @@ proc: BEGIN LEAVE proc; END IF; - -- Invoca al procedimiento que genera el stock virtual de Logiflora, si coincide con la peticion de refresco del disponible - IF vn.isLogifloraDay(vDated, vWarehouse) THEN - -- CALL edi.floramondo_offerRefresh; - SET vIsLogifloraDay = TRUE; - ELSE - SET vIsLogifloraDay = FALSE; - END IF; - -- Calcula algunos parámetros necesarios SET vStartDate = TIMESTAMP(vDated, '00:00:00'); SELECT inventoried INTO vInventoryDate FROM vn.config; + SELECT DATE_SUB(vStartDate, INTERVAL MAX(life) DAY) INTO vLifeScope FROM vn.itemType; SELECT SUBTIME(util.VN_NOW(), reserveTime) INTO vReserveDate FROM hedera.orderConfig; + SELECT w.id INTO vWarehouseFkInventory + FROM vn.warehouse w + WHERE w.code = 'inv'; + -- Calcula el ultimo dia de vida para cada producto DROP TEMPORARY TABLE IF EXISTS itemRange; CREATE TEMPORARY TABLE itemRange (PRIMARY KEY (itemFk)) ENGINE = MEMORY - SELECT c.itemFk, - IF(it.life IS NULL, - NULL, - TIMESTAMP(TIMESTAMPADD(DAY, it.life, c.landing), '23:59:59')) ended - FROM ( - SELECT b.itemFk, MAX(t.landed) landing - FROM vn.buy b - JOIN vn.entry e ON b.entryFk = e.id - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vInventoryDate AND vStartDate - AND t.warehouseInFk = vWarehouse - AND NOT e.isExcludedFromAvailable - GROUP BY b.itemFk - ) c - JOIN vn.item i ON i.id = c.itemFk + SELECT i.id itemFk, + util.dayEnd(DATE_ADD(c.maxLanded, INTERVAL it.life DAY)) ended, it.life + FROM vn.item i + LEFT JOIN ( + SELECT b.itemFk, MAX(t.landed) maxLanded + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + WHERE t.landed BETWEEN vLifeScope AND vStartDate + AND t.warehouseInFk = vWarehouse + AND t.warehouseOutFk <> vWarehouseFkInventory + AND it.life + AND NOT e.isExcludedFromAvailable + GROUP BY b.itemFk + ) c ON i.id = c.itemFk JOIN vn.itemType it ON it.id = i.typeFk - HAVING ended >= vStartDate OR ended IS NULL; + HAVING ended >= vStartDate OR life IS NULL; -- Calcula el ATP DELETE FROM available WHERE calc_id = vCalc; @@ -86,7 +86,7 @@ proc: BEGIN WHERE i.landed >= vStartDate AND (ir.ended IS NULL OR i.landed <= ir.ended) AND i.warehouseInFk = vWarehouse - AND (ISNULL(wf.entryFk) OR vIsLogifloraDay) + AND ISNULL(wf.entryFk) UNION ALL SELECT i.itemFk, i.shipped, i.quantity FROM vn.itemEntryOut i From 18772c04f6efd189efadadc2115178c6e16ed1ad Mon Sep 17 00:00:00 2001 From: Jbreso Date: Wed, 31 Jan 2024 09:38:57 +0100 Subject: [PATCH 09/39] feat: refs #5167 update --- db/dump/fixtures.after.sql | 7 +- db/dump/fixtures.before.sql | 43 +++++----- .../itemPlacementSupplyStockGetTargetList.sql | 21 ++--- .../vn/triggers/warehouse_afterUpdate.sql | 12 --- db/routines/vn/views/warehouseJoined.sql | 6 -- .../vn/views/zoneEstimatedDelivery.sql | 25 ------ .../vn2008/procedures/desglose_volume.sql | 82 ------------------- db/routines/vn2008/views/agency.sql | 1 - db/routines/vn2008/views/v_price_fixed.sql | 35 -------- db/routines/vn2008/views/v_warehouse.sql | 10 --- db/routines/vn2008/views/warehouse_alias.sql | 6 -- .../10857-navyArborvitae/00-firstScript.sql | 6 ++ 12 files changed, 36 insertions(+), 218 deletions(-) delete mode 100644 db/routines/vn/triggers/warehouse_afterUpdate.sql delete mode 100644 db/routines/vn/views/warehouseJoined.sql delete mode 100644 db/routines/vn/views/zoneEstimatedDelivery.sql delete mode 100644 db/routines/vn2008/procedures/desglose_volume.sql delete mode 100644 db/routines/vn2008/views/v_price_fixed.sql delete mode 100644 db/routines/vn2008/views/v_warehouse.sql delete mode 100644 db/routines/vn2008/views/warehouse_alias.sql create mode 100644 db/versions/10857-navyArborvitae/00-firstScript.sql diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index 57ccb8626..4d8f1b9b5 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -73,9 +73,10 @@ INSERT INTO vn.cmr (id, truckPlate, observations, senderInstruccions, paymentIns UPDATE `vn`.`claimRatio` SET `claimAmount` = '10' WHERE (`clientFk` = '1101'); -INSERT INTO `vn`.`agency` (`name`, `warehouseFk`, `warehouseAliasFk`, `isOwn`, `isAnyVolumeAllowed`) VALUES - ('Agencia', '1', '1', '1', '1'), - ('Otra agencia ', '1', '2', '0', '0'); +INSERT INTO `vn`.`agency` (`name`, `warehouseFk`, `isOwn`, `isAnyVolumeAllowed`) + VALUES + ('Agencia', '1', '1', '1'), + ('Otra agencia ', '1', '0', '0'); INSERT INTO `vn`.`expedition` (`agencyModeFk`, `ticketFk`, `isBox`, `counter`, `workerFk`, `externalId`, `packagingFk`, `hostFk`, `itemPackingTypeFk`, `hasNewRoute`) VALUES ('1', '1', 1, '1', '1', '1', '1', 'pc00', 'F', 0), diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 0f608d19d..42049a782 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -174,20 +174,15 @@ INSERT INTO `vn`.`country`(`id`, `country`, `isUeeMember`, `code`, `currencyFk`, (19,'Francia', 1, 'FR', 1, 27, 4, 0, 1), (30,'Canarias', 1, 'IC', 1, 24, 4, 1, 2); -INSERT INTO `vn`.`warehouseAlias`(`id`, `name`) +INSERT INTO `vn`.`warehouse`(`id`, `name`, `code`, `isComparative`, `isInventory`, `hasAvailable`, `isManaged`, `hasDms`, `hasComission`, `countryFk`, `hasProduction`, `isOrigin`, `isDestiny`) VALUES - (1, 'Main Warehouse'), - (2, 'Gotham'); - -INSERT INTO `vn`.`warehouse`(`id`, `name`, `code`, `isComparative`, `isInventory`, `hasAvailable`, `isManaged`, `hasDms`, `hasComission`, `aliasFk`, `countryFk`, `hasProduction`) - VALUES - (1, 'Warehouse One', 'ALG', 1, 1, 1, 1, 1, 1, 2, 1, 1), - (2, 'Warehouse Two', NULL, 1, 1, 1, 1, 0, 1, 2, 13, 1), - (3, 'Warehouse Three', NULL, 1, 1, 1, 1, 0, 0, 2, 1, 1), - (4, 'Warehouse Four', NULL, 1, 1, 1, 1, 0, 0, 2, 1, 1), - (5, 'Warehouse Five', NULL, 1, 1, 1, 1, 0, 0, 2, 1, 1), - (13, 'Inventory', 'inv', 1, 1, 1, 0, 0, 0, 2, 1, 0), - (60, 'Algemesi', NULL, 1, 1, 1, 0, 0, 0, 2, 1, 0); + (1, 'Warehouse One', 'ALG', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), + (2, 'Warehouse Two', NULL, 1, 1, 1, 1, 0, 1, 13, 1, 1, 0), + (3, 'Warehouse Three', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0), + (4, 'Warehouse Four', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1), + (5, 'Warehouse Five', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0), + (13, 'Inventory', 'inv', 1, 1, 1, 0, 0, 0, 1, 0, 0, 0), + (60, 'Algemesi', NULL, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0); INSERT INTO `vn`.`sectorType` (id,description) VALUES (1,'First type'); @@ -271,18 +266,18 @@ INSERT INTO `vn`.`deliveryMethod`(`id`, `code`, `description`) (3, 'PICKUP', 'Recogida'), (4, 'OTHER', 'Otros'); -INSERT INTO `vn`.`agency`(`id`, `name`, `warehouseFk`, `warehouseAliasFk`) +INSERT INTO `vn`.`agency`(`id`, `name`, `warehouseFk`) VALUES - (1, 'inhouse pickup' , 1, 1), - (2, 'Super-Man delivery' , 1, 1), - (3, 'Teleportation device' , 1, 1), - (4, 'Entanglement' , 1, 1), - (5, 'Quantum break device' , 1, 1), - (6, 'Walking' , 1, 1), - (7, 'Gotham247' , 1, 1), - (8, 'Gotham247Expensive' , 1, 1), - (9, 'Refund' , 1, 1), - (10, 'Other agency' , 1, 1); + (1, 'inhouse pickup' , 1), + (2, 'Super-Man delivery' , 1), + (3, 'Teleportation device' , 1), + (4, 'Entanglement' , 1), + (5, 'Quantum break device' , 1), + (6, 'Walking' , 1), + (7, 'Gotham247' , 1), + (8, 'Gotham247Expensive' , 1), + (9, 'Refund' , 1), + (10, 'Other agency' , 1); UPDATE `vn`.`agencyMode` SET `id` = 1 WHERE `name` = 'inhouse pickup'; UPDATE `vn`.`agencyMode` SET `id` = 2 WHERE `name` = 'Super-Man delivery'; diff --git a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql index 424e3438d..e77d88b70 100644 --- a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql +++ b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql @@ -8,27 +8,20 @@ BEGIN * @param vItemFk Identificador de vn.item * @param vSectorFk Identificador de vn.sector */ - DECLARE vWarehouseAliasFk INT; - - SELECT w.aliasFk INTO vWarehouseAliasFk - FROM vn.sector s - JOIN vn.warehouse w ON w.id = s.warehouseFk - WHERE s.id = vSectorFk; - SELECT ish.shelvingFk shelving, - p.code parking, - sum(ish.visible) as stockTotal, - ish.created, - p.pickingOrder + p.code parking, + SUM(ish.visible) as stockTotal, + ish.created, + p.pickingOrder FROM vn.itemShelving ish JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector sc ON sc.id = p.sectorFk JOIN vn.warehouse w ON w.id = sc.warehouseFk - WHERE w.aliasFk = vWarehouseAliasFk + WHERE sc.id = vSectorFk AND ish.visible > 0 AND ish.itemFk = vItemFk GROUP BY ish.id - ORDER BY (sc.id = vSectorFk) DESC, sh.priority DESC, ish.created, p.pickingOrder; + ORDER BY sh.priority DESC, ish.created, p.pickingOrder; END$$ -DELIMITER ; +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/triggers/warehouse_afterUpdate.sql b/db/routines/vn/triggers/warehouse_afterUpdate.sql deleted file mode 100644 index 93f424429..000000000 --- a/db/routines/vn/triggers/warehouse_afterUpdate.sql +++ /dev/null @@ -1,12 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`warehouse_afterUpdate` - AFTER UPDATE ON `warehouse` - FOR EACH ROW -BEGIN - IF NEW.isFeedStock IS TRUE AND OLD.isFeedStock IS FALSE THEN - INSERT IGNORE INTO warehouseAlias(`name`) VALUES(NEW.`name`); - INSERT IGNORE INTO warehouseJoined(warehouseFk, warehouseAliasFk) - VALUES(NEW.id,LAST_INSERT_ID()); - END IF; -END$$ -DELIMITER ; diff --git a/db/routines/vn/views/warehouseJoined.sql b/db/routines/vn/views/warehouseJoined.sql deleted file mode 100644 index dbbb40b1a..000000000 --- a/db/routines/vn/views/warehouseJoined.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`warehouseJoined` -AS SELECT `wj`.`warehouse_id` AS `warehouseFk`, - `wj`.`warehouse_alias_id` AS `warehouseAliasFk` -FROM `vn2008`.`warehouse_joined` `wj` diff --git a/db/routines/vn/views/zoneEstimatedDelivery.sql b/db/routines/vn/views/zoneEstimatedDelivery.sql deleted file mode 100644 index e52d5487e..000000000 --- a/db/routines/vn/views/zoneEstimatedDelivery.sql +++ /dev/null @@ -1,25 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`zoneEstimatedDelivery` - AS SELECT t.zoneFk, - zc.`hour` zoneClosureHour, - z.`hour` zoneHour, - sv.volume volume, - al.hasToRecalcPrice, - lhp.m3, - dl.minSpeed - FROM ticket t - JOIN ticketStateToday tst ON tst.ticket = t.id - JOIN state s ON s.id = tst.state - JOIN saleVolume sv ON sv.ticketFk = t.id - LEFT JOIN lastHourProduction lhp ON lhp.warehouseFk = t.warehouseFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN warehouseAlias wa ON wa.id = w.aliasFk - STRAIGHT_JOIN `zone` z ON z.id = t.zoneFk - LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk - AND zc.dated = util.VN_CURDATE() - LEFT JOIN cache.departure_limit dl ON dl.warehouse_id = t.warehouseFk - AND dl.fecha = util.VN_CURDATE() - JOIN alertLevel al ON al.id = s.alertLevel - WHERE w.hasProduction - AND DATE(t.shipped) = util.VN_CURDATE() diff --git a/db/routines/vn2008/procedures/desglose_volume.sql b/db/routines/vn2008/procedures/desglose_volume.sql deleted file mode 100644 index 3fcad4b71..000000000 --- a/db/routines/vn2008/procedures/desglose_volume.sql +++ /dev/null @@ -1,82 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`desglose_volume`(IN vAgencyFk INT) -BEGIN - - DECLARE vStarted DATETIME DEFAULT TIMESTAMP(util.VN_CURDATE()); - DECLARE vEnded DATETIME DEFAULT TIMESTAMP(util.VN_CURDATE(), '23:59:59'); - DECLARE vIsHolland BOOL; - - SELECT (wa.name = 'Holanda') INTO vIsHolland - FROM vn.agency a - JOIN vn.warehouseAlias wa ON wa.id = a.warehouseAliasFk - WHERE a.id = vAgencyFk; - - IF vIsHolland THEN - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_PackagingEstimated; - CREATE TEMPORARY TABLE tmp.ticket_PackagingEstimated - ( - ticketFk INT PRIMARY KEY - ,carros DECIMAL(5,1) DEFAULT 0 - ); - - INSERT INTO tmp.ticket_PackagingEstimated(ticketFk, carros) - SELECT sv.ticketFk, ROUND(vc.dutchCompressionRate * sum(sv.volume) / vc.trolleyM3,0) - FROM vn.ticket t - JOIN vn.saleVolume sv ON sv.ticketFk = t.id - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN vn.volumeConfig vc - WHERE t.shipped BETWEEN vStarted AND vEnded - AND am.agencyFk = vAgencyFk - GROUP BY t.id; - - SELECT a.nickname Provincia, - count(*) expediciones, - 0 Bultos, - sum(tpe.carros) Prevision - FROM vn.ticket t - JOIN vn.address a ON a.id = t.addressFk - JOIN tmp.ticket_PackagingEstimated tpe ON tpe.ticketFk = t.id - GROUP BY a.nickname; - - ELSE - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_PackagingEstimated; - CREATE TEMPORARY TABLE tmp.ticket_PackagingEstimated - ( - ticketFk INT PRIMARY KEY - ,boxes INT DEFAULT 0 - ); - - INSERT INTO tmp.ticket_PackagingEstimated(ticketFk, boxes) - SELECT sv.ticketFk, CEIL(1000 * sum(sv.volume) / vc.standardFlowerBox) - FROM vn.ticket t - JOIN vn.saleVolume sv ON sv.ticketFk = t.id - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN vn.volumeConfig vc - WHERE t.shipped BETWEEN vStarted AND vEnded - AND IFNULL(t.packages,0) = 0 - AND am.agencyFk = vAgencyFk - GROUP BY t.id; - - - SELECT p.name Provincia, - count(*) expediciones, - sum(t.packages) Bultos, - sum(tpe.boxes) Prevision - FROM vn.ticket t - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON a.provinceFk = p.id - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN tmp.ticket_PackagingEstimated tpe ON tpe.ticketFk = t.id - WHERE t.warehouseFk = 60 - AND t.shipped BETWEEN vStarted AND vEnded - AND am.agencyFk = vAgencyFk - GROUP BY p.name; - - END IF; - SELECT * FROM tmp.ticket_PackagingEstimated; - DROP TEMPORARY TABLE tmp.ticket_PackagingEstimated; - -END$$ -DELIMITER ; diff --git a/db/routines/vn2008/views/agency.sql b/db/routines/vn2008/views/agency.sql index 819fbd009..637bb0910 100644 --- a/db/routines/vn2008/views/agency.sql +++ b/db/routines/vn2008/views/agency.sql @@ -4,7 +4,6 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` AS SELECT `a`.`id` AS `agency_id`, `a`.`name` AS `name`, `a`.`warehouseFk` AS `warehouse_id`, - `a`.`warehouseAliasFk` AS `warehouse_alias_id`, `a`.`isOwn` AS `propios`, `a`.`workCenterFk` AS `workCenterFk` FROM `vn`.`agency` `a` diff --git a/db/routines/vn2008/views/v_price_fixed.sql b/db/routines/vn2008/views/v_price_fixed.sql deleted file mode 100644 index db48e5a46..000000000 --- a/db/routines/vn2008/views/v_price_fixed.sql +++ /dev/null @@ -1,35 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`v_price_fixed` -AS SELECT `pf`.`warehouse_id` AS `warehouse_id`, - `pf`.`item_id` AS `item_id`, - `pf`.`rate_0` AS `rate_0`, - `pf`.`rate_1` AS `rate_1`, - `pf`.`rate_2` AS `rate_2`, - `pf`.`rate_3` AS `rate_3`, - `pf`.`date_start` AS `date_start`, - `pf`.`date_end` AS `date_end`, - `pf`.`bonus` AS `bonus`, - `pf`.`grouping` AS `grouping`, - `pf`.`Packing` AS `Packing`, - `pf`.`caja` AS `caja` -FROM `vn2008`.`price_fixed` `pf` -WHERE `pf`.`warehouse_id` < 1000 -UNION ALL -SELECT `wg`.`warehouse_id` AS `warehouse_id`, - `pf`.`item_id` AS `item_id`, - `pf`.`rate_0` AS `rate_0`, - `pf`.`rate_1` AS `rate_1`, - `pf`.`rate_2` AS `rate_2`, - `pf`.`rate_3` AS `rate_3`, - `pf`.`date_start` AS `date_start`, - `pf`.`date_end` AS `date_end`, - `pf`.`bonus` AS `bonus`, - `pf`.`grouping` AS `grouping`, - `pf`.`Packing` AS `Packing`, - `pf`.`caja` AS `caja` -FROM ( - `vn2008`.`price_fixed` `pf` - JOIN `vn2008`.`warehouse_group` `wg` - ) -WHERE `wg`.`warehouse_alias_id` + 1000 = `pf`.`warehouse_id` diff --git a/db/routines/vn2008/views/v_warehouse.sql b/db/routines/vn2008/views/v_warehouse.sql deleted file mode 100644 index fd17b6a06..000000000 --- a/db/routines/vn2008/views/v_warehouse.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`v_warehouse` -AS SELECT `warehouse`.`id` AS `id`, - `warehouse`.`name` AS `almacen` -FROM `vn2008`.`warehouse` -UNION ALL -SELECT 1000 + `warehouse_alias`.`warehouse_alias_id` AS `warehouse_alias_id`, - concat(`warehouse_alias`.`alias`, '(G)') AS `concat(alias, '(G)')` -FROM `vn2008`.`warehouse_alias` diff --git a/db/routines/vn2008/views/warehouse_alias.sql b/db/routines/vn2008/views/warehouse_alias.sql deleted file mode 100644 index 9a151c9d5..000000000 --- a/db/routines/vn2008/views/warehouse_alias.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`warehouse_alias` -AS SELECT `wa`.`id` AS `warehouse_alias_id`, - `wa`.`name` AS `alias` -FROM `vn`.`warehouseAlias` `wa` diff --git a/db/versions/10857-navyArborvitae/00-firstScript.sql b/db/versions/10857-navyArborvitae/00-firstScript.sql new file mode 100644 index 000000000..f379f54cd --- /dev/null +++ b/db/versions/10857-navyArborvitae/00-firstScript.sql @@ -0,0 +1,6 @@ +ALTER TABLE vn.agency CHANGE warehouseAliasFk warehouseAliasFk__ smallint(5) unsigned DEFAULT NULL NULL COMMENT 'Refs #5167 Deprecated 2024-01-23'; + +ALTER TABLE vn.warehouse CHANGE aliasFk aliasFk__ smallint(5) unsigned DEFAULT NULL NULL COMMENT 'Refs #5167 Deprecated 2024-01-23'; + +RENAME TABLE vn.warehouseAlias TO vn.warehouseAlias__; +ALTER TABLE vn.warehouseAlias__ COMMENT='Refs #5167 Deprecated 2024-01-23'; \ No newline at end of file From aa993e7386809865a40a41ff7059084db6fdac61 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 31 Jan 2024 17:01:47 +0100 Subject: [PATCH 10/39] refs #6757 fix back, fix upperCase, fix e2e back --- db/dump/fixtures.before.sql | 14 +++++++------- db/myt.config.yml | 11 +++++++++++ db/package.json | 13 +++++++++++++ db/versions/10863-brownIvy/00-firstScript.sql | 4 ++++ .../13-supplier/01_summary_and_descriptor.spec.js | 2 +- e2e/paths/13-supplier/03_fiscal_data.spec.js | 4 ++-- loopback/locale/en.json | 3 ++- loopback/locale/es.json | 7 ++++--- .../back/methods/invoice-in/specs/filter.spec.js | 4 ++-- .../back/methods/supplier/specs/getSummary.spec.js | 2 +- .../methods/supplier/specs/newSupplier.spec.js | 4 ++-- .../supplier/specs/updateFiscalData.spec.js | 6 +++--- .../supplier/back/models/specs/supplier.spec.js | 2 +- modules/supplier/back/models/supplier.js | 6 ++++++ modules/supplier/front/create/index.html | 3 ++- 15 files changed, 61 insertions(+), 24 deletions(-) create mode 100755 db/myt.config.yml create mode 100644 db/package.json create mode 100644 db/versions/10863-brownIvy/00-firstScript.sql diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 3803730bd..efc03fc7b 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -569,13 +569,13 @@ INSERT INTO `vn`.`supplierActivity`(`code`, `name`) INSERT INTO `vn`.`supplier`(`id`, `name`, `nickname`,`account`,`countryFk`,`nif`, `commission`, `created`, `isActive`, `street`, `city`, `provinceFk`, `postCode`, `payMethodFk`, `payDemFk`, `payDay`, `taxTypeSageFk`, `withholdingSageFk`, `transactionTypeSageFk`, `workerFk`, `supplierActivityFk`, `isPayMethodChecked`, `healthRegister`) VALUES - (1, 'Plants SL', 'Plants nick', 4100000001, 1, '06089160W', 0, util.VN_CURDATE(), 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'), - (2, 'Farmer King', 'The farmer', 4000020002, 1, '87945234L', 0, util.VN_CURDATE(), 1, 'supplier address 2', 'GOTHAM', 2, 43022, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'), - (69, 'Packaging', 'Packaging nick', 4100000069, 1, '94935005K', 0, util.VN_CURDATE(), 1, 'supplier address 5', 'ASGARD', 3, 46600, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'), - (442, 'Verdnatura Levante SL', 'Verdnatura', 5115000442, 1, '06815934E', 0, util.VN_CURDATE(), 1, 'supplier address 3', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'), - (567, 'Holland', 'Holland nick', 4000020567, 1, '14364089Z', 0, util.VN_CURDATE(), 1, 'supplier address 6', 'ASGARD', 3, 46600, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'), - (791, 'Bros SL', 'Bros nick', 5115000791, 1, '37718083S', 0, util.VN_CURDATE(), 1, 'supplier address 7', 'ASGARD', 3, 46600, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'), - (1381, 'Ornamentales', 'Ornamentales', 7185001381, 1, '07972486L', 0, util.VN_CURDATE(), 1, 'supplier address 4', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'); + (1, 'PLANTS SL', 'Plants nick', 4100000001, 1, '06089160W', 0, util.VN_CURDATE(), 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'), + (2, 'FARMER KING', 'The farmer', 4000020002, 1, '87945234L', 0, util.VN_CURDATE(), 1, 'supplier address 2', 'GOTHAM', 2, 43022, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'), + (69, 'PACKAGING', 'Packaging nick', 4100000069, 1, '94935005K', 0, util.VN_CURDATE(), 1, 'supplier address 5', 'ASGARD', 3, 46600, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'), + (442, 'VERDNATURA LEVANTE SL', 'Verdnatura', 5115000442, 1, '06815934E', 0, util.VN_CURDATE(), 1, 'supplier address 3', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'), + (567, 'HOLLAND', 'Holland nick', 4000020567, 1, '14364089Z', 0, util.VN_CURDATE(), 1, 'supplier address 6', 'ASGARD', 3, 46600, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'), + (791, 'BROS SL', 'Bros nick', 5115000791, 1, '37718083S', 0, util.VN_CURDATE(), 1, 'supplier address 7', 'ASGARD', 3, 46600, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'), + (1381, 'ORNAMENTALES', 'Ornamentales', 7185001381, 1, '07972486L', 0, util.VN_CURDATE(), 1, 'supplier address 4', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'); INSERT INTO `vn`.`supplierAddress`(`id`, `supplierFk`, `nickname`, `street`, `provinceFk`, `postalCode`, `city`, `phone`, `mobile`) VALUES diff --git a/db/myt.config.yml b/db/myt.config.yml new file mode 100755 index 000000000..3fe7ad02f --- /dev/null +++ b/db/myt.config.yml @@ -0,0 +1,11 @@ +code: my-db +schemas: + - myt + - my_db +fixtures: + myt: + - version + - versionLog + my_db: + - table1 + - table2 diff --git a/db/package.json b/db/package.json new file mode 100644 index 000000000..0290ef879 --- /dev/null +++ b/db/package.json @@ -0,0 +1,13 @@ +{ + "name": "my-db", + "version": "1.0.0", + "author": "Me", + "description": "My database project", + "license": "GPL-3.0", + "repository": { + "type": "git" + }, + "dependencies": { + "@verdnatura/myt": "^1.6.3" + } +} \ No newline at end of file diff --git a/db/versions/10863-brownIvy/00-firstScript.sql b/db/versions/10863-brownIvy/00-firstScript.sql new file mode 100644 index 000000000..d3b79ae66 --- /dev/null +++ b/db/versions/10863-brownIvy/00-firstScript.sql @@ -0,0 +1,4 @@ +-- Place your SQL code here +UPDATE vn.supplier + SET name = UPPER(name), + nickname = UPPER(nickname); diff --git a/e2e/paths/13-supplier/01_summary_and_descriptor.spec.js b/e2e/paths/13-supplier/01_summary_and_descriptor.spec.js index 591a6116a..e82f851ea 100644 --- a/e2e/paths/13-supplier/01_summary_and_descriptor.spec.js +++ b/e2e/paths/13-supplier/01_summary_and_descriptor.spec.js @@ -24,7 +24,7 @@ describe('Supplier summary & descriptor path', () => { it(`should confirm there's data on the summary header`, async() => { const result = await page.waitToGetProperty(selectors.supplierSummary.header, 'innerText'); - expect(result).toContain('Plants SL - 1'); + expect(result).toContain('PLANTS SL - 1'); }); it(`should confirm there's data on the summary basic data`, async() => { diff --git a/e2e/paths/13-supplier/03_fiscal_data.spec.js b/e2e/paths/13-supplier/03_fiscal_data.spec.js index 96977e708..ccd9d7809 100644 --- a/e2e/paths/13-supplier/03_fiscal_data.spec.js +++ b/e2e/paths/13-supplier/03_fiscal_data.spec.js @@ -24,7 +24,7 @@ describe('Supplier fiscal data path', () => { country: null, postcode: null, city: 'Valencia', - socialName: 'Farmer King SL', + socialName: 'FARMER KING SL', taxNumber: '12345678Z', account: '0123456789', sageWithholding: 'retencion estimacion objetiva', @@ -46,7 +46,7 @@ describe('Supplier fiscal data path', () => { country: 'España', postcode: '46000', city: 'Valencia', - socialName: 'Farmer King SL', + socialName: 'FARMER KING SL', taxNumber: '12345678Z', account: '0123456789', sageWithholding: 'RETENCION ESTIMACION OBJETIVA', diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 568916bef..c8ecadf8a 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -203,5 +203,6 @@ "Cannot past travels with entries": "Cannot past travels with entries", "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}", "Incorrect pin": "Incorrect pin.", - "The notification subscription of this worker cant be modified": "The notification subscription of this worker cant be modified" + "The notification subscription of this worker cant be modified": "The notification subscription of this worker cant be modified", + "Name should be uppercase": "Name should be uppercase" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 5555ef8b0..73428f5df 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -72,7 +72,7 @@ "The secret can't be blank": "La contraseña no puede estar en blanco", "We weren't able to send this SMS": "No hemos podido enviar el SMS", "This client can't be invoiced": "Este cliente no puede ser facturado", - "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", + "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", "This ticket can't be invoiced": "Este ticket no puede ser facturado", "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", "This ticket can not be modified": "Este ticket no puede ser modificado", @@ -336,5 +336,6 @@ "Incorrect pin": "Pin incorrecto.", "You already have the mailAlias": "Ya tienes este alias de correo", "The alias cant be modified": "Este alias de correo no puede ser modificado", - "No tickets to invoice": "No hay tickets para facturar" -} + "No tickets to invoice": "No hay tickets para facturar", + "Name should be uppercase": "Name should be uppercase" +} \ No newline at end of file diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js index 76f17720f..9834989fc 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js @@ -8,14 +8,14 @@ describe('InvoiceIn filter()', () => { try { const ctx = { args: { - search: 'Plants SL', + search: 'PLANTS SL', } }; const result = await models.InvoiceIn.filter(ctx, {}, options); expect(result.length).toEqual(5); - expect(result[0].supplierName).toEqual('Plants SL'); + expect(result[0].supplierName).toEqual('PLANTS SL'); await tx.rollback(); } catch (e) { diff --git a/modules/supplier/back/methods/supplier/specs/getSummary.spec.js b/modules/supplier/back/methods/supplier/specs/getSummary.spec.js index 30713f517..347851561 100644 --- a/modules/supplier/back/methods/supplier/specs/getSummary.spec.js +++ b/modules/supplier/back/methods/supplier/specs/getSummary.spec.js @@ -5,7 +5,7 @@ describe('Supplier getSummary()', () => { const supplier = await app.models.Supplier.getSummary(1); expect(supplier.id).toEqual(1); - expect(supplier.name).toEqual('Plants SL'); + expect(supplier.name).toEqual('PLANTS SL'); expect(supplier.nif).toEqual('06089160W'); expect(supplier.account).toEqual('4100000001'); expect(supplier.payDay).toEqual(15); diff --git a/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js b/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js index 5fc2ea752..0e7fa0e34 100644 --- a/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js +++ b/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js @@ -25,13 +25,13 @@ describe('Supplier newSupplier()', () => { try { const options = {transaction: tx}; ctx.args = { - name: 'newSupplier', + name: 'NEWSUPPLIER', nif: '12345678Z' }; const result = await models.Supplier.newSupplier(ctx, options); - expect(result.name).toEqual('newSupplier'); + expect(result.name).toEqual('NEWSUPPLIER'); await tx.rollback(); } catch (e) { await tx.rollback(); diff --git a/modules/supplier/back/methods/supplier/specs/updateFiscalData.spec.js b/modules/supplier/back/methods/supplier/specs/updateFiscalData.spec.js index a47e547d1..56030a894 100644 --- a/modules/supplier/back/methods/supplier/specs/updateFiscalData.spec.js +++ b/modules/supplier/back/methods/supplier/specs/updateFiscalData.spec.js @@ -6,7 +6,7 @@ describe('Supplier updateFiscalData', () => { const administrativeId = 5; const employeeId = 1; const defaultData = { - name: 'Plants SL', + name: 'PLANTS SL', nif: '06089160W', account: '4100000001', sageTaxTypeFk: 4, @@ -56,7 +56,7 @@ describe('Supplier updateFiscalData', () => { }); ctx.args = { - name: 'Weapon Dealer', + name: 'WEAPON DEALER', nif: 'A68446004', account: '4000000005', sageTaxTypeFk: 5, @@ -72,7 +72,7 @@ describe('Supplier updateFiscalData', () => { const result = await app.models.Supplier.updateFiscalData(ctx, supplierId); - expect(result.name).toEqual('Weapon Dealer'); + expect(result.name).toEqual('WEAPON DEALER'); expect(result.nif).toEqual('A68446004'); expect(result.account).toEqual('4000000005'); expect(result.sageTaxTypeFk).toEqual(5); diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index fbd3a00db..3f40ce58b 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -129,7 +129,7 @@ describe('loopback model Supplier', () => { const options = {transaction: tx}; try { - const newSupplier = await models.Supplier.create({name: 'Alfred Pennyworth'}, options); + const newSupplier = await models.Supplier.create({name: 'ALFRED PENNYWORTH'}, options); const fetchedSupplier = await models.Supplier.findById(newSupplier.id, null, options); expect(Number(fetchedSupplier.account)).toEqual(4100000000 + newSupplier.id); diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 5cf357c13..0ac389074 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -46,6 +46,12 @@ module.exports = Self => { Self.validateAsync('postCode', hasValidPostcode, { message: `The postcode doesn't exist. Please enter a correct one` }); + Self.validatesFormatOf('name', { + message: 'Name should be uppercase', + allowNull: false, + allowBlank: false, + with: /^[^a-z]*$/ + }); async function hasValidPostcode(err, done) { if (!this.postcode) diff --git a/modules/supplier/front/create/index.html b/modules/supplier/front/create/index.html index eb6e7261e..1e051f3a8 100644 --- a/modules/supplier/front/create/index.html +++ b/modules/supplier/front/create/index.html @@ -12,7 +12,8 @@ + vn-focus + ng-keyup="$ctrl.supplier.name = $ctrl.supplier.name.toUpperCase()"> From 7b1a0e1957fa91ae004525fd00caaaa8a0ca0a49 Mon Sep 17 00:00:00 2001 From: ivanm Date: Thu, 1 Feb 2024 13:02:03 +0100 Subject: [PATCH 11/39] refs #6444 change code according to sql conventions --- .../vn/functions/intrastat_estimateNet.sql | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/db/routines/vn/functions/intrastat_estimateNet.sql b/db/routines/vn/functions/intrastat_estimateNet.sql index 4d66e30de..99a52ded8 100644 --- a/db/routines/vn/functions/intrastat_estimateNet.sql +++ b/db/routines/vn/functions/intrastat_estimateNet.sql @@ -1,19 +1,21 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`intrastat_estimateNet`(intINSTRASTAT INTEGER,intUNIDADES INTEGER) +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`intrastat_estimateNet`(vIntrastat INT, vUnidades INT) RETURNS double DETERMINISTIC BEGIN - DECLARE n DOUBLE; + DECLARE vNet DOUBLE; - SELECT ROUND(intUNIDADES / (SUM(MEDIA) / COUNT(media)), 2) INTO n FROM - (SELECT *, unidades / neto MEDIA - FROM vn2008.intrastat_data - WHERE intrastat_id = intINSTRASTAT AND neto - AND unidades > 0 - ORDER BY odbc_date DESC - LIMIT 20) t; - RETURN n/2; + SELECT ROUND(vUnidades / (SUM(media) / COUNT(media)), 2) INTO vNet + FROM (SELECT *, unidades / neto media + FROM vn2008.intrastat_data + WHERE intrastat_id = vIntrastat + AND neto + AND unidades > 0 + ORDER BY odbc_date DESC + LIMIT 20) t; + + RETURN vNet/2; END$$ DELIMITER ; \ No newline at end of file From 743f317b20879cdde0627a377300ed4b265d3360 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 2 Feb 2024 14:02:16 +0100 Subject: [PATCH 12/39] fix: refs #4466 test & sql --- db/routines/vn/procedures/invoiceIn_add.sql | 237 ++++++++++++++++++ .../00-createAclInvoiceIn.sql | 4 + .../01-createInvoiceInCorrection.sql | 17 ++ .../methods/invoice-in/specs/clone.spec.js | 25 +- 4 files changed, 275 insertions(+), 8 deletions(-) create mode 100644 db/routines/vn/procedures/invoiceIn_add.sql create mode 100644 db/versions/10867-yellowAsparagus/00-createAclInvoiceIn.sql create mode 100644 db/versions/10867-yellowAsparagus/01-createInvoiceInCorrection.sql diff --git a/db/routines/vn/procedures/invoiceIn_add.sql b/db/routines/vn/procedures/invoiceIn_add.sql new file mode 100644 index 000000000..a0979024b --- /dev/null +++ b/db/routines/vn/procedures/invoiceIn_add.sql @@ -0,0 +1,237 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `sage`.`invoiceIn_add`(vInvoiceInFk INT, vXDiarioFk INT) +BEGIN +/** + * Traslada la info de contabilidad relacionada con las facturas recibidas + * + * @vInvoiceInFk Factura recibida + * @vXDiarioFk Id tabla XDiario + */ + DECLARE vInvoiceInOriginalFk INT; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vBase DOUBLE; + DECLARE vVat DOUBLE; + DECLARE vRate DOUBLE; + DECLARE vTransactionCode INT; + DECLARE vCounter INT DEFAULT 0; + DECLARE vTransactionCodeOld INT; + DECLARE vTaxCode INT; + DECLARE vTaxCodeOld INT; + DECLARE vOperationCode VARCHAR(1); + DECLARE vIsIntracommunity BOOL DEFAULT FALSE; + DECLARE vSerialDua VARCHAR(1) DEFAULT 'D'; + DECLARE vInvoiceTypeReceived VARCHAR(1); + DECLARE vInvoiceTypeInformative VARCHAR(1); + DECLARE vIsInformativeExportation BOOL DEFAULT FALSE; + + DECLARE vCursor CURSOR FOR + SELECT it.taxableBase, + CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)), + t.PorcentajeIva, + it.transactionTypeSageFk, + it.taxTypeSageFk, + tty.isIntracommunity, + tt.ClaveOperacionDefecto + FROM vn.invoiceIn i + JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id + JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk + JOIN taxType tty ON tty.id = t.CodigoIva + JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk + LEFT JOIN vn.dua d ON d.id = vInvoiceInFk + WHERE i.id = vInvoiceInFk + AND d.id IS NULL; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DELETE FROM movContaIVA + WHERE id = vXDiarioFk; + + SELECT codeSage INTO vInvoiceTypeReceived + FROM invoiceType WHERE code ='received'; + + SELECT codeSage INTO vInvoiceTypeInformative + FROM invoiceType WHERE code ='informative'; + + INSERT INTO movContaIVA(id, LibreA1) + VALUES (vXDiarioFk, vInvoiceInFk); + + OPEN vCursor; + + l: LOOP + FETCH vCursor INTO vBase, + vVat, + vRate, + vTransactionCode, + vTaxCode, + vIsIntracommunity, + vOperationCode; + + IF vDone THEN + LEAVE l; + END IF; + + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; + + IF vOperationCode IS NOT NULL THEN + UPDATE movContaIVA + SET ClaveOperacionFactura = vOperationCode + WHERE id = vXDiarioFk; + END IF; + + SET vCounter = vCounter + 1; + CASE vCounter + WHEN 1 THEN + UPDATE movContaIVA + SET BaseIva1 = vBase, + PorIva1 = vRate, + CuotaIva1 = vVat, + CodigoTransaccion1 = vTransactionCode, + CodigoIva1 = vTaxCode + WHERE id = vXDiarioFk; + + WHEN 2 THEN + UPDATE movContaIVA + SET BaseIva2 = vBase, + PorIva2 = vRate, + CuotaIva2 = vVat, + CodigoTransaccion2 = vTransactionCode, + CodigoIva2 = vTaxCode + WHERE id = vXDiarioFk; + WHEN 3 THEN + UPDATE movContaIVA + SET BaseIva3 = vBase, + PorIva3 = vRate, + CuotaIva3 = vVat, + CodigoTransaccion3 = vTransactionCode, + CodigoIva3 = vTaxCode + WHERE id = vXDiarioFk; + WHEN 4 THEN + UPDATE movContaIVA + SET BaseIva4 = vBase, + PorIva4 = vRate, + CuotaIva4 = vVat, + CodigoTransaccion4 = vTransactionCode, + CodigoIva4 = vTaxCode + WHERE id = vXDiarioFk; + ELSE + SELECT vXDiarioFk INTO vXDiarioFk; + END CASE; + + IF vIsIntracommunity THEN + UPDATE movContaIVA + SET Intracomunitaria = TRUE + WHERE id = vXDiarioFk; + END IF; + + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; + + END LOOP; + + CLOSE vCursor; + + SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation + FROM vn.dua d + LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN + AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci + WHERE d.ASIEN = ( + SELECT ASIEN + FROM vn.XDiario + WHERE id = vXDiarioFk) + LIMIT 1; + + UPDATE movContaIVA mci + JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk + JOIN vn.XDiario x ON x.id = mci.id + LEFT JOIN tmp.invoiceDua id ON id.id = mci.id + JOIN vn.supplier s ON s.id = ii.supplierFk + JOIN Naciones n ON n.countryFk = s.countryFk + SET mci.CodigoDivisa = ii.currencyFk, + mci.Año = YEAR(ii.issued), + mci.Serie = ii.serial, + mci.Factura = ii.id, + mci.FechaFactura = ii.issued, + mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + + IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + + IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + + IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0), + mci.TipoFactura = IF(id.id, + IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), + IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)), + mci.CodigoCuentaFactura = x.SUBCTA, + mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif), + mci.Nombre = s.name, + mci.SiglaNacion = n.SiglaNacion, + mci.EjercicioFactura = YEAR(ii.issued), + mci.FechaOperacion = ii.issued, + mci.MantenerAsiento = TRUE, + mci.SuFacturaNo = ii.supplierRef, + mci.IvaDeducible1 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva1, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + mci.IvaDeducible2 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva2, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + mci.IvaDeducible3 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva3, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + mci.IvaDeducible4 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva4, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + mci.FechaFacturaOriginal = x.FECHA_EX + WHERE mci.id = vXDiarioFk; + + -- RETENCIONES + UPDATE movContaIVA mci + JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk + JOIN vn.XDiario x ON x.id = mci.id + JOIN vn.supplier s ON s.id = supplierFk + JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id + JOIN vn.expense e ON e.id = iit.expenseFk + JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk + LEFT JOIN tmp.invoiceDua id ON id.id = mci.id + JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase + FROM vn.XDiario x1 + JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN + WHERE x2.BASEEURO <> 0 + AND x1.id = vXDiarioFk + )sub + JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio' + SET mci.CodigoRetencion = t.CodigoRetencion, + mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura), + mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase), + mci.PorRetencion = t.PorcentajeRetencion, + mci.ImporteRetencion = iit.taxableBase * - 1 + WHERE mci.id = vXDiarioFk + AND e.name = 'Retenciones' + AND id.id IS NULL; + + -- SAGE + SELECT correctedFk INTO vInvoiceInOriginalFk + FROM vn.invoiceInCorrection + WHERE correctingFk = vInvoiceInFk; + + IF vInvoiceInOriginalFk THEN + + UPDATE movContaIVA mci + JOIN vn.invoiceInRefund iir ON iir.invoiceInRefundFk = vInvoiceInFk + JOIN (SELECT issued, + SUM(sub.taxableBase) taxableBase, + SUM(ROUND((sub.taxableBase * sub.PorcentajeIva) / 100 , 2)) vat + FROM(SELECT issued, + SUM(iit.taxableBase) taxableBase, + ti.PorcentajeIva + FROM vn.invoiceIn i + JOIN vn.invoiceInTax iit ON iit.invoiceInFk = i.id + JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk + WHERE i.id = vInvoiceInOriginalFk + GROUP BY ti.CodigoIva)sub + )invoiceInOriginal + JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa' + SET mci.TipoRectificativa = iir.refundCategoryFk, + mci.ClaseAbonoRectificativas = iir.refundType, + mci.FechaFacturaOriginal = invoiceInOriginal.issued, + mci.FechaOperacion = invoiceInOriginal.issued, + mci.BaseImponibleOriginal = invoiceInOriginal.taxableBase, + mci.CuotaIvaOriginal = invoiceInOriginal.vat, + mci.ClaveOperacionFactura = co.ClaveOperacionFactura_ + WHERE mci.id = vXDiarioFk; + + END IF; + + +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/versions/10867-yellowAsparagus/00-createAclInvoiceIn.sql b/db/versions/10867-yellowAsparagus/00-createAclInvoiceIn.sql new file mode 100644 index 000000000..927903d47 --- /dev/null +++ b/db/versions/10867-yellowAsparagus/00-createAclInvoiceIn.sql @@ -0,0 +1,4 @@ +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('InvoiceIn', 'corrective', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceInCorrection', '*', '*', 'ALLOW', 'ROLE', 'administrative'); \ No newline at end of file diff --git a/db/versions/10867-yellowAsparagus/01-createInvoiceInCorrection.sql b/db/versions/10867-yellowAsparagus/01-createInvoiceInCorrection.sql new file mode 100644 index 000000000..0d084da9e --- /dev/null +++ b/db/versions/10867-yellowAsparagus/01-createInvoiceInCorrection.sql @@ -0,0 +1,17 @@ +CREATE TABLE IF NOT EXISTS `vn`.`invoiceInCorrection` ( + `correctingFk` mediumint(8) UNSIGNED NOT NULL COMMENT 'Factura rectificativa', + `correctedFk` mediumint(8) UNSIGNED NOT NULL COMMENT 'Factura rectificada', + `cplusRectificationTypeFk` int(10) UNSIGNED NOT NULL, + `siiTypeInvoiceOutFk` int(10) UNSIGNED NOT NULL, + `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT 3, + PRIMARY KEY (`correctingFk`), + KEY `invoiceInCorrection_correctedFk` (`correctedFk`), + KEY `invoiceInCorrection_cplusRectificationTypeFk` (`cplusRectificationTypeFk`), + KEY `invoiceInCorrection_siiTypeInvoiceOut` (`siiTypeInvoiceOutFk`), + KEY `invoiceInCorrection_invoiceCorrectionTypeFk` (`invoiceCorrectionTypeFk`), + CONSTRAINT `invoiceInCorrection_correctedFk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_correctingFk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_siiTypeInvoiceOut` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_invoiceCorrectionTypeFk` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceInCorrection_cplusRectificationTypeFk` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE +); \ No newline at end of file diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js index 42ebe52b3..b6c0fb160 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js @@ -30,17 +30,26 @@ describe('invoiceIn clone()', () => { const options = {transaction: tx}; try { - const clone = await models.InvoiceIn.clone(ctx, 1, options); + const clone = await models.InvoiceIn.clone(ctx, 1, false, options); expect(clone.supplierRef).toEqual('1234(2)'); + const invoiceIn = await models.InvoiceIn.findOne({ + include: [ + { + relation: 'invoiceInTax', + }, + { + relation: 'invoiceInDueDay', + } + ], where: { + id: clone.id + } + }, options); + const invoiceInTax = invoiceIn.invoiceInTax(); + const invoiceInDueDay = invoiceIn.invoiceInDueDay(); - const invoiceInTaxes = await models.InvoiceInTax.find({where: {invoiceInFk: clone.id}}, options); - - expect(invoiceInTaxes.length).toEqual(2); - - const invoiceInDueDays = await models.InvoiceInDueDay.find({where: {invoiceInFk: clone.id}}, options); - - expect(invoiceInDueDays.length).toEqual(2); + expect(invoiceInTax.length).toEqual(2); + expect(invoiceInDueDay.length).toEqual(2); await tx.rollback(); } catch (e) { From 0bd4602568ab04e78c125efff39b081d9e7a9616 Mon Sep 17 00:00:00 2001 From: ivanm Date: Fri, 2 Feb 2024 15:50:16 +0100 Subject: [PATCH 13/39] refs #6445 remove red function and modify precedures --- db/routines/bs/procedures/comercialesCompleto.sql | 14 +++++++------- db/routines/vn2008/functions/red.sql | 14 -------------- db/versions/10866-whiteRaphis/00-firstScript.sql | 1 + 3 files changed, 8 insertions(+), 21 deletions(-) delete mode 100644 db/routines/vn2008/functions/red.sql create mode 100644 db/versions/10866-whiteRaphis/00-firstScript.sql diff --git a/db/routines/bs/procedures/comercialesCompleto.sql b/db/routines/bs/procedures/comercialesCompleto.sql index 323d5cd00..2b8019175 100644 --- a/db/routines/bs/procedures/comercialesCompleto.sql +++ b/db/routines/bs/procedures/comercialesCompleto.sql @@ -20,16 +20,16 @@ BEGIN c.movil, c.POBLACION poblacion, p.`name` provincia, - vn2008.red(f.futur) futur, + ROUND(f.futur, 2) futur, c.Credito credito, pm.`name` forma_pago, - vn2008.red(c365 / 12) consumo_medio365, - vn2008.red(c365) consumo365, - vn2008.red(CmLy.peso) peso_mes_año_pasado, - vn2008.red(CmLy.peso * 1.19) objetivo, + ROUND(c365 / 12, 2) consumo_medio365, + ROUND(c365, 2) consumo365, + ROUND(CmLy.peso, 2) peso_mes_año_pasado, + ROUND(CmLy.peso * 1.19, 2) objetivo, tr.CodigoTrabajador, - vn2008.red(mes_actual.consumo) consumoMes, - vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo, + ROUND(mes_actual.consumo, 2) consumoMes, + ROUND(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0), 2) como_lo_llevo, DATE(LastTicket) ultimo_ticket, dead.muerto, g.Greuge, diff --git a/db/routines/vn2008/functions/red.sql b/db/routines/vn2008/functions/red.sql deleted file mode 100644 index b94e3d716..000000000 --- a/db/routines/vn2008/functions/red.sql +++ /dev/null @@ -1,14 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn2008`.`red`(intCANTIDAD DOUBLE) - RETURNS double - DETERMINISTIC -BEGIN - - DECLARE n DOUBLE; - - SET n = SIGN(intCANTIDAD) * TRUNCATE( (ABS(intCANTIDAD) * 100) + 0.5001 ,0) /100 ; - - RETURN n; - -END$$ -DELIMITER ; diff --git a/db/versions/10866-whiteRaphis/00-firstScript.sql b/db/versions/10866-whiteRaphis/00-firstScript.sql new file mode 100644 index 000000000..bfbcb5dc9 --- /dev/null +++ b/db/versions/10866-whiteRaphis/00-firstScript.sql @@ -0,0 +1 @@ +REVOKE EXECUTE ON FUNCTION vn2008.red FROM hrBoss, salesPerson; From 2a6dc0c478104cc8cafccd7a9e0c2dd32a3f027c Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 2 Feb 2024 15:56:05 +0100 Subject: [PATCH 14/39] fix: refs #4466 spaces --- db/routines/vn/procedures/invoiceIn_add.sql | 59 ++++++++++----------- 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/db/routines/vn/procedures/invoiceIn_add.sql b/db/routines/vn/procedures/invoiceIn_add.sql index a0979024b..0898d6810 100644 --- a/db/routines/vn/procedures/invoiceIn_add.sql +++ b/db/routines/vn/procedures/invoiceIn_add.sql @@ -198,40 +198,37 @@ BEGIN WHERE mci.id = vXDiarioFk AND e.name = 'Retenciones' AND id.id IS NULL; - - -- SAGE - SELECT correctedFk INTO vInvoiceInOriginalFk - FROM vn.invoiceInCorrection - WHERE correctingFk = vInvoiceInFk; - - IF vInvoiceInOriginalFk THEN - UPDATE movContaIVA mci - JOIN vn.invoiceInRefund iir ON iir.invoiceInRefundFk = vInvoiceInFk - JOIN (SELECT issued, - SUM(sub.taxableBase) taxableBase, - SUM(ROUND((sub.taxableBase * sub.PorcentajeIva) / 100 , 2)) vat - FROM(SELECT issued, - SUM(iit.taxableBase) taxableBase, - ti.PorcentajeIva - FROM vn.invoiceIn i - JOIN vn.invoiceInTax iit ON iit.invoiceInFk = i.id - JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk - WHERE i.id = vInvoiceInOriginalFk - GROUP BY ti.CodigoIva)sub - )invoiceInOriginal - JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa' - SET mci.TipoRectificativa = iir.refundCategoryFk, - mci.ClaseAbonoRectificativas = iir.refundType, - mci.FechaFacturaOriginal = invoiceInOriginal.issued, - mci.FechaOperacion = invoiceInOriginal.issued, - mci.BaseImponibleOriginal = invoiceInOriginal.taxableBase, - mci.CuotaIvaOriginal = invoiceInOriginal.vat, - mci.ClaveOperacionFactura = co.ClaveOperacionFactura_ - WHERE mci.id = vXDiarioFk; + SELECT correctedFk INTO vInvoiceInOriginalFk + FROM vn.invoiceInCorrection + WHERE correctingFk = vInvoiceInFk; - END IF; + IF vInvoiceInOriginalFk THEN + UPDATE movContaIVA mci + JOIN vn.invoiceInRefund iir ON iir.invoiceInRefundFk = vInvoiceInFk + JOIN (SELECT issued, + SUM(sub.taxableBase) taxableBase, + SUM(ROUND((sub.taxableBase * sub.PorcentajeIva) / 100 , 2)) vat + FROM(SELECT issued, + SUM(iit.taxableBase) taxableBase, + ti.PorcentajeIva + FROM vn.invoiceIn i + JOIN vn.invoiceInTax iit ON iit.invoiceInFk = i.id + JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk + WHERE i.id = vInvoiceInOriginalFk + GROUP BY ti.CodigoIva)sub + )invoiceInOriginal + JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa' + SET mci.TipoRectificativa = iir.refundCategoryFk, + mci.ClaseAbonoRectificativas = iir.refundType, + mci.FechaFacturaOriginal = invoiceInOriginal.issued, + mci.FechaOperacion = invoiceInOriginal.issued, + mci.BaseImponibleOriginal = invoiceInOriginal.taxableBase, + mci.CuotaIvaOriginal = invoiceInOriginal.vat, + mci.ClaveOperacionFactura = co.ClaveOperacionFactura_ + WHERE mci.id = vXDiarioFk; + END IF; END$$ DELIMITER ; \ No newline at end of file From f4591aae85b6d73df9a6f9f3514df3db3204917a Mon Sep 17 00:00:00 2001 From: Jbreso Date: Mon, 5 Feb 2024 08:07:12 +0100 Subject: [PATCH 15/39] feat: refs #5167 Restaurar zoneEstimatedDelivery --- .../vn/views/zoneEstimatedDelivery.sql | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 db/routines/vn/views/zoneEstimatedDelivery.sql diff --git a/db/routines/vn/views/zoneEstimatedDelivery.sql b/db/routines/vn/views/zoneEstimatedDelivery.sql new file mode 100644 index 000000000..a58286efc --- /dev/null +++ b/db/routines/vn/views/zoneEstimatedDelivery.sql @@ -0,0 +1,24 @@ +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn`.`zoneEstimatedDelivery` + AS SELECT t.zoneFk, + zc.`hour` zoneClosureHour, + z.`hour` zoneHour, + sv.volume volume, + al.hasToRecalcPrice, + lhp.m3, + dl.minSpeed + FROM ticket t + JOIN ticketStateToday tst ON tst.ticket = t.id + JOIN state s ON s.id = tst.state + JOIN saleVolume sv ON sv.ticketFk = t.id + LEFT JOIN lastHourProduction lhp ON lhp.warehouseFk = t.warehouseFk + JOIN warehouse w ON w.id = t.warehouseFk + STRAIGHT_JOIN `zone` z ON z.id = t.zoneFk + LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk + AND zc.dated = util.VN_CURDATE() + LEFT JOIN cache.departure_limit dl ON dl.warehouse_id = t.warehouseFk + AND dl.fecha = util.VN_CURDATE() + JOIN alertLevel al ON al.id = s.alertLevel + WHERE w.hasProduction + AND DATE(t.shipped) = util.VN_CURDATE() From 1a869766b9ed7cf8a46ba35cd331111e56e645fc Mon Sep 17 00:00:00 2001 From: ivanm Date: Mon, 5 Feb 2024 08:32:45 +0100 Subject: [PATCH 16/39] refs #6444 change code accord to conventions --- .../vn/functions/intrastat_estimateNet.sql | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/db/routines/vn/functions/intrastat_estimateNet.sql b/db/routines/vn/functions/intrastat_estimateNet.sql index 99a52ded8..3ee1ca80f 100644 --- a/db/routines/vn/functions/intrastat_estimateNet.sql +++ b/db/routines/vn/functions/intrastat_estimateNet.sql @@ -1,21 +1,32 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`intrastat_estimateNet`(vIntrastat INT, vUnidades INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`intrastat_estimateNet`( + vSelf INT, + vUnits INT +) RETURNS double DETERMINISTIC BEGIN - +/** +* Calcula un valor neto estimado en función de +* datos históricos de facturas intrastat. +* +* @param vSelf Id de intrastat +* @param vUnits Número de unidades +* @return vNet +*/ DECLARE vNet DOUBLE; - SELECT ROUND(vUnidades / (SUM(media) / COUNT(media)), 2) INTO vNet - FROM (SELECT *, unidades / neto media - FROM vn2008.intrastat_data - WHERE intrastat_id = vIntrastat - AND neto - AND unidades > 0 - ORDER BY odbc_date DESC - LIMIT 20) t; + SELECT ROUND(vUnits / (SUM(average) / COUNT(average)), 2) INTO vNet + FROM ( + SELECT *, stems / net average + FROM invoiceInIntrastat + WHERE intrastatFk = vSelf + AND net + AND stems > 0 + ORDER BY dated DESC + LIMIT 20 + ) sub; RETURN vNet/2; - END$$ DELIMITER ; \ No newline at end of file From 05478b43f25e119caf731f9473609e8a5127cbe5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 5 Feb 2024 09:30:29 +0100 Subject: [PATCH 17/39] fix: refs #4466 test back --- modules/invoiceIn/back/methods/invoice-in/clone.js | 4 +--- .../ticket/back/methods/sale/specs/clone.spec.js | 14 +++----------- 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/modules/invoiceIn/back/methods/invoice-in/clone.js b/modules/invoiceIn/back/methods/invoice-in/clone.js index ce1ec178d..88ea0ddcd 100644 --- a/modules/invoiceIn/back/methods/invoice-in/clone.js +++ b/modules/invoiceIn/back/methods/invoice-in/clone.js @@ -110,9 +110,7 @@ module.exports = Self => { foreignValue: dueDated.foreignValue, }, myOptions)); } - } - - if (isRectification) { + } else { for (let intrastat of invoiceInIntrastat) { promises.push(models.InvoiceInIntrastat.create({ invoiceInFk: clone.id, diff --git a/modules/ticket/back/methods/sale/specs/clone.spec.js b/modules/ticket/back/methods/sale/specs/clone.spec.js index f52f7ba38..e2220c028 100644 --- a/modules/ticket/back/methods/sale/specs/clone.spec.js +++ b/modules/ticket/back/methods/sale/specs/clone.spec.js @@ -70,19 +70,11 @@ describe('Ticket cloning - clone function', () => { it('should create a ticket without sales', async() => { const servicesIds = [4]; - const tx = await models.Sale.beginTransaction({}); - const options = {transaction: tx}; - try { - const tickets = await models.Sale.clone(ctx, null, servicesIds, false, options); - const refundedTicket = await getTicketRefund(tickets[0].id, options); - expect(refundedTicket).toBeDefined(); + const tickets = await models.Sale.clone(ctx, null, servicesIds, false, false, options); + const refundedTicket = await getTicketRefund(tickets[0].id, options); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + expect(refundedTicket).toBeDefined(); }); }); From a0c5b1fff6f27d9be04370c085a3395753138132 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 5 Feb 2024 11:59:51 +0100 Subject: [PATCH 18/39] feat: refs # test corrective & clone --- .../methods/invoice-in/specs/clone.spec.js | 104 ++++++++++-------- .../invoice-in/specs/corrective.spec.js | 49 +++++++++ 2 files changed, 109 insertions(+), 44 deletions(-) create mode 100644 modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js index b6c0fb160..436306aab 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js @@ -2,59 +2,75 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('invoiceIn clone()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } + let ctx; + let options; + let tx; + + beforeEach(async() => { + ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'http://localhost'} + }, + args: {} }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx + active: ctx.req }); + + options = {transaction: tx}; + tx = await models.Sale.beginTransaction({}); + options.transaction = tx; + }); + + afterEach(async() => { + await tx.rollback(); }); it('should return the cloned invoiceIn and also clone invoiceInDueDays and invoiceInTaxes if there are any referencing the invoiceIn', async() => { - const userId = 1; - const ctx = { - req: { + const clone = await models.InvoiceIn.clone(ctx, 1, false, options); - accessToken: {userId: userId}, - headers: {origin: 'http://localhost:5000'}, - } - }; - - const tx = await models.InvoiceIn.beginTransaction({}); - const options = {transaction: tx}; - - try { - const clone = await models.InvoiceIn.clone(ctx, 1, false, options); - - expect(clone.supplierRef).toEqual('1234(2)'); - const invoiceIn = await models.InvoiceIn.findOne({ - include: [ - { - relation: 'invoiceInTax', - }, - { - relation: 'invoiceInDueDay', - } - ], where: { - id: clone.id + expect(clone.supplierRef).toEqual('1234(2)'); + const invoiceIn = await models.InvoiceIn.findOne({ + include: [ + { + relation: 'invoiceInTax', + }, + { + relation: 'invoiceInDueDay', } - }, options); - const invoiceInTax = invoiceIn.invoiceInTax(); - const invoiceInDueDay = invoiceIn.invoiceInDueDay(); + ], where: { + id: clone.id + } + }, options); + const invoiceInTax = invoiceIn.invoiceInTax(); + const invoiceInDueDay = invoiceIn.invoiceInDueDay(); - expect(invoiceInTax.length).toEqual(2); - expect(invoiceInDueDay.length).toEqual(2); + expect(invoiceInTax.length).toEqual(2); + expect(invoiceInDueDay.length).toEqual(2); + }); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + it('should return the cloned invoiceIn and also clone invoiceInIntrastat and invoiceInTaxes if it is rectificative', async() => { + const clone = await models.InvoiceIn.clone(ctx, 1, true, options); + + expect(clone.supplierRef).toEqual('1234(2)'); + const invoiceIn = await models.InvoiceIn.findOne({ + include: [ + { + relation: 'invoiceInTax', + }, + { + relation: 'invoiceInIntrastat', + } + ], where: { + id: clone.id + } + }, options); + const invoiceInTax = invoiceIn.invoiceInTax(); + const invoiceInIntrastat = invoiceIn.invoiceInIntrastat(); + + expect(invoiceInTax.length).toEqual(2); + expect(invoiceInIntrastat.length).toEqual(2); }); }); diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js new file mode 100644 index 000000000..1047cd028 --- /dev/null +++ b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js @@ -0,0 +1,49 @@ +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); + +describe('invoiceIn corrective()', () => { + let ctx; + let options; + let tx; + + beforeEach(async() => { + ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'http://localhost'} + }, + args: {} + }; + + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: ctx.req + }); + + options = {transaction: tx}; + tx = await models.Sale.beginTransaction({}); + options.transaction = tx; + }); + + afterEach(async() => { + await tx.rollback(); + }); + + it('La función corrective debería devolver un id cuando se ejecuta correctamente', async() => { + const originalId = 1; + const invoiceReason = 3; + const invoiceType = 2; + const invoiceClass = 1; + const cloneId = await models.InvoiceIn.corrective(ctx, + originalId, invoiceReason, invoiceType, invoiceClass, options); + + expect(cloneId).toBeDefined(); + + const correction = await models.InvoiceInCorrection.findOne({ + where: {correctedFk: originalId, correctingFk: cloneId} + }, options); + + expect(correction.cplusRectificationTypeFk).toEqual(invoiceType); + expect(correction.siiTypeInvoiceOutFk).toEqual(invoiceClass); + expect(correction.invoiceCorrectionTypeFk).toEqual(invoiceReason); + }); +}); From 9247a802bd8999bdc18e58f0db68511fb459e43a Mon Sep 17 00:00:00 2001 From: ivanm Date: Mon, 5 Feb 2024 12:21:11 +0100 Subject: [PATCH 19/39] refs #6665 delete unused views --- db/routines/vn2008/views/Articles_botanical.sql | 7 ------- db/routines/vn2008/views/bionic_updating_options.sql | 6 ------ db/routines/vn2008/views/businessReasonEnd.sql | 6 ------ db/routines/vn2008/views/cl_dev.sql | 6 ------ db/routines/vn2008/views/cl_est.sql | 7 ------- 5 files changed, 32 deletions(-) delete mode 100644 db/routines/vn2008/views/Articles_botanical.sql delete mode 100644 db/routines/vn2008/views/bionic_updating_options.sql delete mode 100644 db/routines/vn2008/views/businessReasonEnd.sql delete mode 100644 db/routines/vn2008/views/cl_dev.sql delete mode 100644 db/routines/vn2008/views/cl_est.sql diff --git a/db/routines/vn2008/views/Articles_botanical.sql b/db/routines/vn2008/views/Articles_botanical.sql deleted file mode 100644 index 44edda655..000000000 --- a/db/routines/vn2008/views/Articles_botanical.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`Articles_botanical` -AS SELECT `ab`.`itemFk` AS `Id_Article`, - `ab`.`genusFk` AS `genus_id`, - `ab`.`specieFk` AS `specie_id` -FROM `vn`.`itemBotanical` `ab` diff --git a/db/routines/vn2008/views/bionic_updating_options.sql b/db/routines/vn2008/views/bionic_updating_options.sql deleted file mode 100644 index 7ee531238..000000000 --- a/db/routines/vn2008/views/bionic_updating_options.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`bionic_updating_options` -AS SELECT `t`.`id` AS `buo_id`, - `t`.`description` AS `description` -FROM `vn`.`ticketUpdateAction` `t` diff --git a/db/routines/vn2008/views/businessReasonEnd.sql b/db/routines/vn2008/views/businessReasonEnd.sql deleted file mode 100644 index 459a33a8b..000000000 --- a/db/routines/vn2008/views/businessReasonEnd.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`businessReasonEnd` -AS SELECT `b`.`id` AS `id`, - `b`.`reason` AS `reason` -FROM `vn`.`businessReasonEnd` `b` diff --git a/db/routines/vn2008/views/cl_dev.sql b/db/routines/vn2008/views/cl_dev.sql deleted file mode 100644 index 7364fe833..000000000 --- a/db/routines/vn2008/views/cl_dev.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`cl_dev` -AS SELECT `c`.`id` AS `id`, - `c`.`description` AS `devolucion` -FROM `vn`.`claimRedelivery` `c` diff --git a/db/routines/vn2008/views/cl_est.sql b/db/routines/vn2008/views/cl_est.sql deleted file mode 100644 index 8aa6ecb2e..000000000 --- a/db/routines/vn2008/views/cl_est.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`cl_est` -AS SELECT `c`.`id` AS `id`, - `c`.`description` AS `estado`, - `c`.`roleFk` AS `roleFk` -FROM `vn`.`claimState` `c` From 6fb198f5796463c66e82770fc35c71caa070a6b4 Mon Sep 17 00:00:00 2001 From: ivanm Date: Mon, 5 Feb 2024 13:09:35 +0100 Subject: [PATCH 20/39] refs #6665 revoke permissions --- db/versions/10871-wheatCyca/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/10871-wheatCyca/00-firstScript.sql diff --git a/db/versions/10871-wheatCyca/00-firstScript.sql b/db/versions/10871-wheatCyca/00-firstScript.sql new file mode 100644 index 000000000..62aff7dac --- /dev/null +++ b/db/versions/10871-wheatCyca/00-firstScript.sql @@ -0,0 +1 @@ +REVOKE SELECT ON TABLE vn2008.Articles_botanical FROM buyer, administrative; From 9f6807204d80705139b01557a0875266476a40d9 Mon Sep 17 00:00:00 2001 From: Jbreso Date: Tue, 6 Feb 2024 08:05:30 +0100 Subject: [PATCH 21/39] feat: refs #5167 changes required --- .../itemPlacementSupplyStockGetTargetList.sql | 12 +++++++----- db/versions/10857-navyArborvitae/00-firstScript.sql | 2 +- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql index e77d88b70..bdc13ae9d 100644 --- a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql +++ b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql @@ -10,7 +10,7 @@ BEGIN */ SELECT ish.shelvingFk shelving, p.code parking, - SUM(ish.visible) as stockTotal, + SUM(ish.visible) stockTotal, ish.created, p.pickingOrder FROM vn.itemShelving ish @@ -18,10 +18,12 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector sc ON sc.id = p.sectorFk JOIN vn.warehouse w ON w.id = sc.warehouseFk - WHERE sc.id = vSectorFk - AND ish.visible > 0 - AND ish.itemFk = vItemFk + WHERE sc.id = vSectorFk + AND ish.visible > 0 + AND ish.itemFk = vItemFk GROUP BY ish.id - ORDER BY sh.priority DESC, ish.created, p.pickingOrder; + ORDER BY sh.priority DESC, + ish.created, + p.pickingOrder; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/versions/10857-navyArborvitae/00-firstScript.sql b/db/versions/10857-navyArborvitae/00-firstScript.sql index f379f54cd..78b0f8c8c 100644 --- a/db/versions/10857-navyArborvitae/00-firstScript.sql +++ b/db/versions/10857-navyArborvitae/00-firstScript.sql @@ -3,4 +3,4 @@ ALTER TABLE vn.agency CHANGE warehouseAliasFk warehouseAliasFk__ smallint(5) uns ALTER TABLE vn.warehouse CHANGE aliasFk aliasFk__ smallint(5) unsigned DEFAULT NULL NULL COMMENT 'Refs #5167 Deprecated 2024-01-23'; RENAME TABLE vn.warehouseAlias TO vn.warehouseAlias__; -ALTER TABLE vn.warehouseAlias__ COMMENT='Refs #5167 Deprecated 2024-01-23'; \ No newline at end of file +ALTER TABLE vn.warehouseAlias__ COMMENT='@Deprecated 2024-01-23 Refs #5167'; \ No newline at end of file From 8ccaacbc07a70e9769c8d31ad4e1e385b4cc2f30 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 6 Feb 2024 08:15:25 +0100 Subject: [PATCH 22/39] fix: refs# 6642 Bug apply version --- db/routines/vn/procedures/itemShelvingRadar.sql | 10 ++++++++-- db/routines/vn/views/itemShelvingAvailable.sql | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/itemShelvingRadar.sql b/db/routines/vn/procedures/itemShelvingRadar.sql index 778bd9910..c860d239e 100644 --- a/db/routines/vn/procedures/itemShelvingRadar.sql +++ b/db/routines/vn/procedures/itemShelvingRadar.sql @@ -1,7 +1,13 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingRadar`(vSectorFk INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingRadar`( + vSectorFk INT +) proc:BEGIN - +/** + * Calcula la información detallada respecto un sector. + * + * @param vSectorFk Id de sector + */ DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE hasFatherSector BOOLEAN; diff --git a/db/routines/vn/views/itemShelvingAvailable.sql b/db/routines/vn/views/itemShelvingAvailable.sql index 868d6a963..ee4ef62b6 100644 --- a/db/routines/vn/views/itemShelvingAvailable.sql +++ b/db/routines/vn/views/itemShelvingAvailable.sql @@ -1,7 +1,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vn`.`itemShelvingAvailable` -AS SELECT `s`.`id` AS `saleFk`, +AS SELECT `s`.`id` `saleFk`, `tst`.`updated` AS `Modificado`, `s`.`ticketFk` AS `ticketFk`, 0 AS `isPicked`, From a72acbb08f5c89ba77b6a342c10382138dbf5372 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 6 Feb 2024 08:21:34 +0100 Subject: [PATCH 23/39] fix: refs# 6642 Bug apply version --- db/routines/vn/views/itemShelvingAvailable.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/views/itemShelvingAvailable.sql b/db/routines/vn/views/itemShelvingAvailable.sql index c9513d6f1..ee4ef62b6 100644 --- a/db/routines/vn/views/itemShelvingAvailable.sql +++ b/db/routines/vn/views/itemShelvingAvailable.sql @@ -38,7 +38,7 @@ FROM ( ) JOIN `vn`.`agencyMode` `am` ON(`am`.`id` = `t`.`agencyModeFk`) ) - JOIN `vn`.`ticketStateToday` `tst` ON(`tst`.`ticket` = `t`.`id`) + JOIN `vn`.`ticketStateToday` `tst` ON(`tst`.`ticketFk` = `t`.`id`) ) JOIN `vn`.`state` `st` ON(`st`.`id` = `tst`.`state`) ) From 438af34d73a5b85c3b0ffe8cb2f989275fc0f936 Mon Sep 17 00:00:00 2001 From: ivanm Date: Tue, 6 Feb 2024 08:40:06 +0100 Subject: [PATCH 24/39] refs #6444 cambio vUnits por vStems --- db/routines/vn/functions/intrastat_estimateNet.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/functions/intrastat_estimateNet.sql b/db/routines/vn/functions/intrastat_estimateNet.sql index 3ee1ca80f..350cb788a 100644 --- a/db/routines/vn/functions/intrastat_estimateNet.sql +++ b/db/routines/vn/functions/intrastat_estimateNet.sql @@ -1,7 +1,7 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`intrastat_estimateNet`( vSelf INT, - vUnits INT + vStems INT ) RETURNS double DETERMINISTIC @@ -11,12 +11,12 @@ BEGIN * datos históricos de facturas intrastat. * * @param vSelf Id de intrastat -* @param vUnits Número de unidades +* @param vStems Número de unidades * @return vNet */ DECLARE vNet DOUBLE; - SELECT ROUND(vUnits / (SUM(average) / COUNT(average)), 2) INTO vNet + SELECT ROUND(vStems / (SUM(average) / COUNT(average)), 2) INTO vNet FROM ( SELECT *, stems / net average FROM invoiceInIntrastat From 7ebb9cb429aa2f4717bc5d59f4cb60b2281e81e2 Mon Sep 17 00:00:00 2001 From: Jbreso Date: Tue, 6 Feb 2024 09:55:47 +0100 Subject: [PATCH 25/39] feat: refs #5167 change required --- db/versions/10857-navyArborvitae/00-firstScript.sql | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/db/versions/10857-navyArborvitae/00-firstScript.sql b/db/versions/10857-navyArborvitae/00-firstScript.sql index 78b0f8c8c..507ddcfaa 100644 --- a/db/versions/10857-navyArborvitae/00-firstScript.sql +++ b/db/versions/10857-navyArborvitae/00-firstScript.sql @@ -1,6 +1,8 @@ -ALTER TABLE vn.agency CHANGE warehouseAliasFk warehouseAliasFk__ smallint(5) unsigned DEFAULT NULL NULL COMMENT 'Refs #5167 Deprecated 2024-01-23'; +ALTER TABLE vn.agency + CHANGE warehouseAliasFk warehouseAliasFk__ SMALLINT(5) unsigned DEFAULT NULL NULL COMMENT '@Deprecated 2024-01-23 Refs #5167'; -ALTER TABLE vn.warehouse CHANGE aliasFk aliasFk__ smallint(5) unsigned DEFAULT NULL NULL COMMENT 'Refs #5167 Deprecated 2024-01-23'; +ALTER TABLE vn.warehouse + CHANGE aliasFk aliasFk__ SMALLINT(5) UNSIGNED DEFAULT NULL NULL COMMENT '@Deprecated 2024-01-23 Refs #5167'; RENAME TABLE vn.warehouseAlias TO vn.warehouseAlias__; ALTER TABLE vn.warehouseAlias__ COMMENT='@Deprecated 2024-01-23 Refs #5167'; \ No newline at end of file From 6002c6cd7a54f22df561d453758853784596d210 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 6 Feb 2024 10:07:39 +0100 Subject: [PATCH 26/39] refs #6757 fix trad --- db/myt.config.yml | 11 ----------- db/package.json | 13 ------------- loopback/locale/es.json | 4 ++-- 3 files changed, 2 insertions(+), 26 deletions(-) delete mode 100755 db/myt.config.yml delete mode 100644 db/package.json diff --git a/db/myt.config.yml b/db/myt.config.yml deleted file mode 100755 index 3fe7ad02f..000000000 --- a/db/myt.config.yml +++ /dev/null @@ -1,11 +0,0 @@ -code: my-db -schemas: - - myt - - my_db -fixtures: - myt: - - version - - versionLog - my_db: - - table1 - - table2 diff --git a/db/package.json b/db/package.json deleted file mode 100644 index 0290ef879..000000000 --- a/db/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "my-db", - "version": "1.0.0", - "author": "Me", - "description": "My database project", - "license": "GPL-3.0", - "repository": { - "type": "git" - }, - "dependencies": { - "@verdnatura/myt": "^1.6.3" - } -} \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 7db2489ae..f6bfe43fc 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -337,5 +337,5 @@ "You already have the mailAlias": "Ya tienes este alias de correo", "The alias cant be modified": "Este alias de correo no puede ser modificado", "No tickets to invoice": "No hay tickets para facturar", - "Name should be uppercase": "Name should be uppercase" -} \ No newline at end of file + "Name should be uppercase": "El nombre debe ir en mayúscula" +} From a949c25860aad740d350b7f9b025668338e5e13f Mon Sep 17 00:00:00 2001 From: Jbreso Date: Tue, 6 Feb 2024 10:09:39 +0100 Subject: [PATCH 27/39] feat refs #5167 changes required --- db/versions/10857-navyArborvitae/00-firstScript.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/versions/10857-navyArborvitae/00-firstScript.sql b/db/versions/10857-navyArborvitae/00-firstScript.sql index 507ddcfaa..64e4d5282 100644 --- a/db/versions/10857-navyArborvitae/00-firstScript.sql +++ b/db/versions/10857-navyArborvitae/00-firstScript.sql @@ -1,8 +1,8 @@ ALTER TABLE vn.agency - CHANGE warehouseAliasFk warehouseAliasFk__ SMALLINT(5) unsigned DEFAULT NULL NULL COMMENT '@Deprecated 2024-01-23 Refs #5167'; + CHANGE warehouseAliasFk warehouseAliasFk__ SMALLINT(5) UNSIGNED DEFAULT NULL NULL COMMENT '@deprecated 2024-01-23 refs #5167'; ALTER TABLE vn.warehouse - CHANGE aliasFk aliasFk__ SMALLINT(5) UNSIGNED DEFAULT NULL NULL COMMENT '@Deprecated 2024-01-23 Refs #5167'; + CHANGE aliasFk aliasFk__ SMALLINT(5) UNSIGNED DEFAULT NULL NULL COMMENT '@deprecated 2024-01-23 refs #5167'; RENAME TABLE vn.warehouseAlias TO vn.warehouseAlias__; -ALTER TABLE vn.warehouseAlias__ COMMENT='@Deprecated 2024-01-23 Refs #5167'; \ No newline at end of file +ALTER TABLE vn.warehouseAlias__ COMMENT='@deprecated 2024-01-23 refs #5167'; \ No newline at end of file From b3e658f9aabb6a18a5bc7058ad98f7c46a29b3ce Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 10:20:04 +0100 Subject: [PATCH 28/39] ci: refs#6706 Jenkinsfile fixes --- Jenkinsfile | 106 +++++++++++++++++++++++++++++----------------------- 1 file changed, 59 insertions(+), 47 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index bd19e8e15..28c5e4775 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -5,34 +5,36 @@ def FROM_GIT def RUN_TESTS def RUN_BUILD -pre: { - switch (env.BRANCH_NAME) { - case 'test': - env.NODE_ENV = 'test' - env.BACK_REPLICAS = 2 - break - case 'master': - env.NODE_ENV = 'production' - env.BACK_REPLICAS = 4 - break - default: - env.NODE_ENV = 'dev' - env.BACK_REPLICAS = 1 +node { + stage('Setup') { + switch (env.BRANCH_NAME) { + case 'test': + env.NODE_ENV = 'test' + env.BACK_REPLICAS = 2 + break + case 'master': + env.NODE_ENV = 'production' + env.BACK_REPLICAS = 4 + break + default: + env.NODE_ENV = 'dev' + env.BACK_REPLICAS = 1 + } + + PROTECTED_BRANCH = [ + 'dev', + 'test', + 'master' + ].contains(env.BRANCH_NAME) + + FROM_GIT = env.JOB_NAME.startsWith('gitea/') + RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT + RUN_BUILD = PROTECTED_BRANCH && FROM_GIT + + // Uncomment to enable debugging + // https://loopback.io/doc/en/lb3/Setting-debug-strings.html#debug-strings-reference + //env.DEBUG = 'strong-remoting:shared-method' } - - PROTECTED_BRANCH = [ - 'dev', - 'test', - 'master' - ].contains(env.BRANCH_NAME) - - FROM_GIT = env.JOB_NAME.startsWith('gitea/') - RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT - RUN_BUILD = PROTECTED_BRANCH && FROM_GIT - - // Uncomment to enable debugging - // https://loopback.io/doc/en/lb3/Setting-debug-strings.html#debug-strings-reference - //env.DEBUG = 'strong-remoting:shared-method' } pipeline { agent any @@ -47,29 +49,47 @@ pipeline { STACK_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}" } stages { + stage('Install') { + environment { + NODE_ENV = '' + } + parallel { + stage('Back') { + steps { + sh 'pnpm install --prefer-offline' + } + } + stage('Print') { + when { + expression { FROM_GIT } + } + steps { + sh 'pnpm install --prefer-offline --prefix=print' + } + } + stage('Front') { + when { + expression { FROM_GIT } + } + steps { + sh 'pnpm install --prefer-offline --prefix=front' + } + } + } + } stage('Stack') { environment { - NODE_ENV = "" TZ = 'Europe/Madrid' } parallel { stage('Back') { stages { - stage('Install') { - environment { - NODE_ENV = "" - } - steps { - sh 'pnpm install --prefer-offline' - sh 'pnpm install --prefer-offline --prefix=print' - } - } stage('Test') { when { expression { RUN_TESTS } } environment { - NODE_ENV = "" + NODE_ENV = '' } steps { sh 'npm run test:back:ci' @@ -106,20 +126,12 @@ pipeline { expression { FROM_GIT } } stages { - stage('Install') { - environment { - NODE_ENV = "" - } - steps { - sh 'pnpm install --prefer-offline --prefix=front' - } - } stage('Test') { when { expression { RUN_TESTS } } environment { - NODE_ENV = "" + NODE_ENV = '' } steps { sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=10' From f8155539c691503d81b324b40ef602c0e006e985 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 10:38:11 +0100 Subject: [PATCH 29/39] ci: refs#6706 Jenkinsfile fixes --- Jenkinsfile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Jenkinsfile b/Jenkinsfile index 28c5e4775..7087b7d8a 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -34,6 +34,9 @@ node { // Uncomment to enable debugging // https://loopback.io/doc/en/lb3/Setting-debug-strings.html#debug-strings-reference //env.DEBUG = 'strong-remoting:shared-method' + + echo "Node: ${NODE_NAME}" + echo "Workspace: ${WORKSPACE}" } } pipeline { From 50af5154f48e9beacb63d200954f66d62e2a333a Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 10:54:32 +0100 Subject: [PATCH 30/39] ci: refs#6706 Jenkinsfile load environemnt --- Jenkinsfile | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 7087b7d8a..c30e96343 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -31,10 +31,14 @@ node { RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT RUN_BUILD = PROTECTED_BRANCH && FROM_GIT - // Uncomment to enable debugging - // https://loopback.io/doc/en/lb3/Setting-debug-strings.html#debug-strings-reference - //env.DEBUG = 'strong-remoting:shared-method' + configFileProvider([ + configFile(fileId: "salix.groovy", + variable: 'GROOVY_FILE') + ]) { + load env.GROOVY_FILE + } + // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables echo "Node: ${NODE_NAME}" echo "Workspace: ${WORKSPACE}" } From e581247954f73f0e17a3f15f70675f3c20360a2b Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 11:27:14 +0100 Subject: [PATCH 31/39] ci: refs#6706 Jenkinsfile load properties from config --- Jenkinsfile | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index c30e96343..e44499c44 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -7,18 +7,25 @@ def RUN_BUILD node { stage('Setup') { - switch (env.BRANCH_NAME) { - case 'test': - env.NODE_ENV = 'test' - env.BACK_REPLICAS = 2 - break - case 'master': - env.NODE_ENV = 'production' - env.BACK_REPLICAS = 4 - break - default: - env.NODE_ENV = 'dev' - env.BACK_REPLICAS = 1 + env.NODE_ENV = 'dev' + + configFileProvider([ + configFile(fileId: 'salix.properties', + variable: 'PROPS_FILE') + ]) { + def props = readProperties file: PROPS_FILE + env.DEBUG = props.DEBUG + } + + if (PROTECTED_BRANCH) { + configFileProvider([ + configFile(fileId: "salix.branch.${env.BRANCH_NAME}", + variable: 'BRANCH_PROPS_FILE') + ]) { + def props = readProperties file: BRANCH_PROPS_FILE + env.BACK_REPLICAS = props.BACK_REPLICAS + env.NODE_ENV = props.NODE_ENV + } } PROTECTED_BRANCH = [ @@ -31,16 +38,10 @@ node { RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT RUN_BUILD = PROTECTED_BRANCH && FROM_GIT - configFileProvider([ - configFile(fileId: "salix.groovy", - variable: 'GROOVY_FILE') - ]) { - load env.GROOVY_FILE - } - // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables echo "Node: ${NODE_NAME}" echo "Workspace: ${WORKSPACE}" + echo "Debug: ${env.DEBUG}" } } pipeline { From 4af454edd407293904e3a425acdade49688d6ea7 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 11:38:30 +0100 Subject: [PATCH 32/39] ci: refs#6706 Jenkinsfile debug --- Jenkinsfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Jenkinsfile b/Jenkinsfile index e44499c44..a1341dc98 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -42,6 +42,7 @@ node { echo "Node: ${NODE_NAME}" echo "Workspace: ${WORKSPACE}" echo "Debug: ${env.DEBUG}" + echo "Replicas: ${env.BACK_REPLICAS}" } } pipeline { From 28168130aea1cc25ada69ebba416b5c8a9b11dff Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 11:40:13 +0100 Subject: [PATCH 33/39] ci: refs#6706 Jenkinsfile fixes --- Jenkinsfile | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index a1341dc98..a49405cdc 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -9,6 +9,16 @@ node { stage('Setup') { env.NODE_ENV = 'dev' + PROTECTED_BRANCH = [ + 'dev', + 'test', + 'master' + ].contains(env.BRANCH_NAME) + + FROM_GIT = env.JOB_NAME.startsWith('gitea/') + RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT + RUN_BUILD = PROTECTED_BRANCH && FROM_GIT + configFileProvider([ configFile(fileId: 'salix.properties', variable: 'PROPS_FILE') @@ -28,21 +38,10 @@ node { } } - PROTECTED_BRANCH = [ - 'dev', - 'test', - 'master' - ].contains(env.BRANCH_NAME) - - FROM_GIT = env.JOB_NAME.startsWith('gitea/') - RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT - RUN_BUILD = PROTECTED_BRANCH && FROM_GIT - // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables echo "Node: ${NODE_NAME}" echo "Workspace: ${WORKSPACE}" echo "Debug: ${env.DEBUG}" - echo "Replicas: ${env.BACK_REPLICAS}" } } pipeline { From 19080e348af53374ba03090a0bb4664ac552e5bd Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 12:11:03 +0100 Subject: [PATCH 34/39] ci: refs#6706 Jenkinsfile print properties --- Jenkinsfile | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index a49405cdc..20baa8ace 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -19,12 +19,17 @@ node { RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT RUN_BUILD = PROTECTED_BRANCH && FROM_GIT + // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables + echo "Node: ${env.NODE_NAME}" + echo "Workspace: ${env.WORKSPACE}" + configFileProvider([ configFile(fileId: 'salix.properties', variable: 'PROPS_FILE') ]) { def props = readProperties file: PROPS_FILE - env.DEBUG = props.DEBUG + props.each { key, value -> env[key] = value } + props.each { key, value -> println "${key}: ${value}" } } if (PROTECTED_BRANCH) { @@ -33,15 +38,10 @@ node { variable: 'BRANCH_PROPS_FILE') ]) { def props = readProperties file: BRANCH_PROPS_FILE - env.BACK_REPLICAS = props.BACK_REPLICAS - env.NODE_ENV = props.NODE_ENV + props.each { key, value -> env[key] = value } + props.each { key, value -> println "${key}: ${value}" } } } - - // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables - echo "Node: ${NODE_NAME}" - echo "Workspace: ${WORKSPACE}" - echo "Debug: ${env.DEBUG}" } } pipeline { From 5c48d8c6b97a2347a95118a1ee1b56a44aa81e32 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 12:12:09 +0100 Subject: [PATCH 35/39] ci: refs#6706 Jenkinsfile fixes --- Jenkinsfile | 2 -- 1 file changed, 2 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 20baa8ace..a0442422c 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -29,7 +29,6 @@ node { ]) { def props = readProperties file: PROPS_FILE props.each { key, value -> env[key] = value } - props.each { key, value -> println "${key}: ${value}" } } if (PROTECTED_BRANCH) { @@ -39,7 +38,6 @@ node { ]) { def props = readProperties file: BRANCH_PROPS_FILE props.each { key, value -> env[key] = value } - props.each { key, value -> println "${key}: ${value}" } } } } From 4067108258f94893f05c7add66e56bbf3f8a3e92 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 12:14:00 +0100 Subject: [PATCH 36/39] ci: refs#6706 Jenkinsfile fixes --- Jenkinsfile | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index a0442422c..a8091121a 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -19,16 +19,12 @@ node { RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT RUN_BUILD = PROTECTED_BRANCH && FROM_GIT - // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables - echo "Node: ${env.NODE_NAME}" - echo "Workspace: ${env.WORKSPACE}" - configFileProvider([ configFile(fileId: 'salix.properties', variable: 'PROPS_FILE') ]) { def props = readProperties file: PROPS_FILE - props.each { key, value -> env[key] = value } + env.DEBUG = props.DEBUG } if (PROTECTED_BRANCH) { @@ -37,9 +33,15 @@ node { variable: 'BRANCH_PROPS_FILE') ]) { def props = readProperties file: BRANCH_PROPS_FILE - props.each { key, value -> env[key] = value } + env.BACK_REPLICAS = props.BACK_REPLICAS + env.NODE_ENV = props.NODE_ENV } } + + // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables + echo "Node: ${env.NODE_NAME}" + echo "Workspace: ${env.WORKSPACE}" + echo "Debug: ${env.DEBUG}" } } pipeline { From 4c123247d81029641ae2363742613b7ae2ab00ed Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 12:16:49 +0100 Subject: [PATCH 37/39] ci: refs#6706 Jenkinsfile fixes --- Jenkinsfile | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index a8091121a..4f6504f3a 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -19,12 +19,18 @@ node { RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT RUN_BUILD = PROTECTED_BRANCH && FROM_GIT + // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables + echo "Node: ${env.NODE_NAME}" + echo "Workspace: ${env.WORKSPACE}" + echo "Debug: ${env.DEBUG}" + configFileProvider([ configFile(fileId: 'salix.properties', variable: 'PROPS_FILE') ]) { def props = readProperties file: PROPS_FILE - env.DEBUG = props.DEBUG + props.each {key, value -> env.put(key, value) } + props.each {key, value -> echo "${key}: ${value}" } } if (PROTECTED_BRANCH) { @@ -33,15 +39,10 @@ node { variable: 'BRANCH_PROPS_FILE') ]) { def props = readProperties file: BRANCH_PROPS_FILE - env.BACK_REPLICAS = props.BACK_REPLICAS - env.NODE_ENV = props.NODE_ENV + props.each {key, value -> env.put(key, value) } + props.each {key, value -> echo "${key}: ${value}" } } } - - // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables - echo "Node: ${env.NODE_NAME}" - echo "Workspace: ${env.WORKSPACE}" - echo "Debug: ${env.DEBUG}" } } pipeline { From 9c2ec2b8dd33564346760032b2669bcc92952083 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 12:17:45 +0100 Subject: [PATCH 38/39] ci: refs#6706 Jenkinsfile fixes --- Jenkinsfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 4f6504f3a..80db9b344 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -29,7 +29,7 @@ node { variable: 'PROPS_FILE') ]) { def props = readProperties file: PROPS_FILE - props.each {key, value -> env.put(key, value) } + props.each {key, value -> env."${key}" = value } props.each {key, value -> echo "${key}: ${value}" } } @@ -39,7 +39,7 @@ node { variable: 'BRANCH_PROPS_FILE') ]) { def props = readProperties file: BRANCH_PROPS_FILE - props.each {key, value -> env.put(key, value) } + props.each {key, value -> env."${key}" = value } props.each {key, value -> echo "${key}: ${value}" } } } From f909c648a7e644895c0d9b98ba0b6c845419f6a6 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 6 Feb 2024 12:21:06 +0100 Subject: [PATCH 39/39] ci: refs#6706 Jenkinsfile fixes --- Jenkinsfile | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 80db9b344..56e33f4ae 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -20,9 +20,8 @@ node { RUN_BUILD = PROTECTED_BRANCH && FROM_GIT // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables - echo "Node: ${env.NODE_NAME}" - echo "Workspace: ${env.WORKSPACE}" - echo "Debug: ${env.DEBUG}" + echo "NODE_NAME: ${env.NODE_NAME}" + echo "WORKSPACE: ${env.WORKSPACE}" configFileProvider([ configFile(fileId: 'salix.properties',