From 2797a731c548b83185af42abebf9044c39ce0b07 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 25 Jun 2024 12:00:49 +0200 Subject: [PATCH 01/42] refs #6952 subName --- .../reports/delivery-note/delivery-note.html | 3 ++- .../reports/delivery-note/locale/en.yml | 5 +++-- .../reports/delivery-note/locale/es.yml | 5 +++-- .../reports/delivery-note/locale/fr.yml | 7 ++++--- .../reports/delivery-note/locale/pt.yml | 5 +++-- .../reports/delivery-note/sql/sales.sql | 19 ++++++++++--------- 6 files changed, 25 insertions(+), 19 deletions(-) diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html index 92dd1b126..540a80a3a 100644 --- a/print/templates/reports/delivery-note/delivery-note.html +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -81,6 +81,7 @@ {{sale.tag5}} {{sale.value5}} {{sale.tag6}} {{sale.value6}} {{sale.tag7}} {{sale.value7}} + {{$t('producer')}} {{ sale.subName }} @@ -249,4 +250,4 @@ v-bind:center-text="client.socialName" v-bind="$props"> - \ No newline at end of file + diff --git a/print/templates/reports/delivery-note/locale/en.yml b/print/templates/reports/delivery-note/locale/en.yml index 5902da8b3..84b31e494 100644 --- a/print/templates/reports/delivery-note/locale/en.yml +++ b/print/templates/reports/delivery-note/locale/en.yml @@ -20,6 +20,7 @@ vatType: VAT Type digitalSignature: Digital signature plantPassport: Plant passport packages: Packages +producer: Producer services: title: Services theader: @@ -44,7 +45,7 @@ taxes: taxBase: Tax base tax: Tax fee: Fee - tfoot: + tfoot: subtotal: Subtotal total: Total -observations: Observations \ No newline at end of file +observations: Observations diff --git a/print/templates/reports/delivery-note/locale/es.yml b/print/templates/reports/delivery-note/locale/es.yml index d87198f45..891e59d77 100644 --- a/print/templates/reports/delivery-note/locale/es.yml +++ b/print/templates/reports/delivery-note/locale/es.yml @@ -15,6 +15,7 @@ discount: Dto. vat: IVA amount: Importe total: Total +producer: Productor subtotal: Subtotal vatType: Tipo de IVA digitalSignature: Firma digital @@ -45,7 +46,7 @@ taxes: taxBase: Base imp. tax: Tasa fee: Cuota - tfoot: + tfoot: subtotal: Subtotal total: Total -observations: Observaciones \ No newline at end of file +observations: Observaciones diff --git a/print/templates/reports/delivery-note/locale/fr.yml b/print/templates/reports/delivery-note/locale/fr.yml index 603623a47..87cd2bcde 100644 --- a/print/templates/reports/delivery-note/locale/fr.yml +++ b/print/templates/reports/delivery-note/locale/fr.yml @@ -14,7 +14,8 @@ price: PRIX/u discount: Remise vat: TVA amount: Montant -total: Total +producer: producteur +total: Total subtotal: Total partiel vatType: Type de TVA digitalSignature: Signature numérique @@ -45,7 +46,7 @@ taxes: taxBase: Base imposable tax: Taxe fee: Quote - tfoot: + tfoot: subtotal: Total partiel total: Total -observations: Observations \ No newline at end of file +observations: Observations diff --git a/print/templates/reports/delivery-note/locale/pt.yml b/print/templates/reports/delivery-note/locale/pt.yml index fb49d230b..be39eb3f0 100644 --- a/print/templates/reports/delivery-note/locale/pt.yml +++ b/print/templates/reports/delivery-note/locale/pt.yml @@ -14,6 +14,7 @@ price: PVP/u discount: Dto. vat: IVA amount: Importe +producer: Produtor total: Total subtotal: Sub-total vatType: Tipo de IVA @@ -45,7 +46,7 @@ taxes: taxBase: Tributável tax: Taxa fee: Compartilhado - tfoot: + tfoot: subtotal: Subtotal total: Total -observations: Observações \ No newline at end of file +observations: Observações diff --git a/print/templates/reports/delivery-note/sql/sales.sql b/print/templates/reports/delivery-note/sql/sales.sql index c449030cf..4cbffa12f 100644 --- a/print/templates/reports/delivery-note/sql/sales.sql +++ b/print/templates/reports/delivery-note/sql/sales.sql @@ -1,4 +1,4 @@ -SELECT +SELECT s.id, s.itemFk, s.concept, @@ -15,12 +15,13 @@ SELECT s.ticketFk, tcl.code vatType, ib.ediBotanic botanical, - i.tag5, + i.tag5, i.value5, - i.tag6, - i.value6, - i.tag7, - i.value7 + i.tag6, + i.value6, + i.tag7, + i.value7, + i.subName FROM vn.sale s LEFT JOIN saleComponent sc ON sc.saleFk = s.id LEFT JOIN component cr ON cr.id = sc.componentFk @@ -32,12 +33,12 @@ FROM vn.sale s LEFT JOIN supplier sp ON sp.id = t.companyFk LEFT JOIN itemType it ON it.id = i.typeFk LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id - AND itc.countryFk = sp.countryFk + LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id + AND itc.countryFk = sp.countryFk LEFT JOIN taxClass tcl ON tcl.id = itc.taxClassFk LEFT JOIN itemBotanicalWithGenus ib ON ib.itemFk = i.id AND ic.code = 'plant' AND ib.ediBotanic IS NOT NULL WHERE s.ticketFk = ? GROUP BY s.id -ORDER BY (it.isPackaging), s.concept, s.itemFk \ No newline at end of file +ORDER BY (it.isPackaging), s.concept, s.itemFk From 0240734a4b99c4003ce909e7aeba121e2c062b8f Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 1 Jul 2024 11:50:37 +0200 Subject: [PATCH 02/42] refs #6897 fix filter --- modules/entry/back/methods/entry/filter.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 1cd12b737..f3f14e7c1 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -173,7 +173,8 @@ module.exports = Self => { s.name AS supplierName, s.nickname AS supplierAlias, co.code AS companyCode, - cu.code AS currencyCode + cu.code AS currencyCode, + t.ref AS travelRef FROM vn.entry e JOIN vn.supplier s ON s.id = e.supplierFk JOIN vn.travel t ON t.id = e.travelFk From 7f213a7435550314bb71556a89c6f97062ef681e Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 2 Jul 2024 12:02:44 +0200 Subject: [PATCH 03/42] refs #6952 fix producer --- print/templates/reports/delivery-note/delivery-note.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html index 540a80a3a..c1701e084 100644 --- a/print/templates/reports/delivery-note/delivery-note.html +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -81,7 +81,7 @@ {{sale.tag5}} {{sale.value5}} {{sale.tag6}} {{sale.value6}} {{sale.tag7}} {{sale.value7}} - {{$t('producer')}} {{ sale.subName }} + {{$t('producer')}} {{ sale.subName }} From d1ef1c80f8271026905e45fd2790160984ae5de1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 09:36:20 +0200 Subject: [PATCH 04/42] feat: refs #7382 Added unique key --- db/versions/11127-silverMoss/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/11127-silverMoss/00-firstScript.sql diff --git a/db/versions/11127-silverMoss/00-firstScript.sql b/db/versions/11127-silverMoss/00-firstScript.sql new file mode 100644 index 000000000..aae2e857e --- /dev/null +++ b/db/versions/11127-silverMoss/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.invoiceInTax ADD CONSTRAINT invoiceInTax_unique UNIQUE KEY (invoiceInFk,expenseFk); From 77d86c9fd979fe92aaa4b416c73c07a25f392f3d Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 09:55:14 +0200 Subject: [PATCH 05/42] feat: refs #7664 Added created in calendar table --- db/versions/11128-turquoiseCymbidium/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/11128-turquoiseCymbidium/00-firstScript.sql diff --git a/db/versions/11128-turquoiseCymbidium/00-firstScript.sql b/db/versions/11128-turquoiseCymbidium/00-firstScript.sql new file mode 100644 index 000000000..4f6cafcf8 --- /dev/null +++ b/db/versions/11128-turquoiseCymbidium/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.calendar ADD created timestamp DEFAULT current_timestamp() NOT NULL AFTER dated; From aaca2d12c5e2eda72d92a0fc109806b6ae4e3336 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 10:20:20 +0200 Subject: [PATCH 06/42] refactor: refs #7504 Rename id greuge --- db/versions/11129-limeHydrangea/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/11129-limeHydrangea/00-firstScript.sql diff --git a/db/versions/11129-limeHydrangea/00-firstScript.sql b/db/versions/11129-limeHydrangea/00-firstScript.sql new file mode 100644 index 000000000..eb2320ee1 --- /dev/null +++ b/db/versions/11129-limeHydrangea/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.greuge CHANGE Id id int(10) unsigned auto_increment NOT NULL; From fafebb4339c76ea80d4d29ccc34165a66e244db6 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 3 Jul 2024 12:13:40 +0200 Subject: [PATCH 07/42] refs #6897 fix filter --- modules/entry/back/methods/entry/filter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index df5fef1bc..69bcb46da 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -180,7 +180,7 @@ module.exports = Self => { cu.code currencyCode, t.shipped, t.landed, - t.ref AS travelRef + t.ref AS travelRef, t.warehouseInFk, w.name warehouseInName FROM vn.entry e From 900fa2de5ed71fb921517578787e930a35e889c7 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 3 Jul 2024 13:03:19 +0200 Subject: [PATCH 08/42] fix: refs #7648 add myOpts --- modules/entry/back/methods/entry/filter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 69bcb46da..5989494a4 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -146,7 +146,7 @@ module.exports = Self => { }); filter = mergeFilters(ctx.args.filter, {where}); const userId = ctx.req.accessToken.userId; - const isSupplier = await Self.app.models.Supplier.findById(userId, options); + const isSupplier = await Self.app.models.Supplier.findById(userId, myOptions); if (isSupplier) { if (!filter.where) filter.where = {}; filter.where[`e.supplierFk`] = ctx.req.accessToken.userId; From 4f9552379ed043f5d334e588fc9678085e7a9929 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 3 Jul 2024 13:46:19 +0200 Subject: [PATCH 09/42] feat: refs #7654 entry_splitByShelving --- .../vn/procedures/entry_splitByShelving.sql | 170 ++++++++---------- .../11131-brownPhormium/00-firstScript.sql | 1 + 2 files changed, 80 insertions(+), 91 deletions(-) create mode 100644 db/versions/11131-brownPhormium/00-firstScript.sql diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index 2898141ea..839bf02d1 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -9,70 +9,81 @@ BEGIN * @param vToEntryFk Entrada destino */ DECLARE vBuyFk INT; - DECLARE vIshStickers INT; - DECLARE vBuyStickers INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; - - DECLARE cur CURSOR FOR - SELECT bb.id buyFk, - FLOOR(ish.visible / ish.packing) ishStickers, - bb.stickers buyStickers - FROM vn.itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b - WHERE b.entryFk = vFromEntryFk - ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - AND bb.stickers >= FLOOR(ish.visible / ish.packing) - WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci - GROUP BY ish.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE vIshStickers INT; + DECLARE vBuyStickers INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; - -- Cantidades de la matrícula que exceden la de las entradas - SELECT ish.itemFk, - i.longName, - FLOOR(ish.visible / ish.packing) AS etiEnMatricula, - bb.stickers etiEnEntrada - FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - LEFT JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b - WHERE b.entryFk = vFromEntryFk - ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci - AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing) - GROUP BY ish.id; - - OPEN cur; - - read_loop: LOOP - SET vDone = FALSE; + DECLARE cur CURSOR FOR + SELECT bb.id buyFk, + FLOOR(ish.visible / ish.packing) ishStickers, + bb.stickers buyStickers + FROM itemShelving ish + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM buy b + WHERE b.entryFk = vFromEntryFk + ORDER BY b.stickers DESC + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + AND bb.stickers >= FLOOR(ish.visible / ish.packing) + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + AND NOT ish.isSplit + GROUP BY ish.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; + OPEN cur; - IF vDone THEN - LEAVE read_loop; - END IF; + read_loop: LOOP + SET vDone = FALSE; - IF vIshStickers = vBuyStickers THEN - UPDATE vn.buy - SET entryFk = vToEntryFk - WHERE id = vBuyFk; - ELSE - UPDATE vn.buy - SET stickers = stickers - vIshStickers, - quantity = stickers * packing - WHERE id = vBuyFk; - - INSERT INTO vn.buy(entryFk, + FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; + + IF vDone THEN + LEAVE read_loop; + END IF; + + IF vIshStickers = vBuyStickers THEN + UPDATE buy + SET entryFk = vToEntryFk + WHERE id = vBuyFk; + ELSE + UPDATE buy + SET stickers = stickers - vIshStickers, + quantity = stickers * packing + WHERE id = vBuyFk; + + INSERT INTO buy(entryFk, + itemFk, + quantity, + buyingValue, + freightValue, + isIgnored, + stickers, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + location, + packagingFk, + price1, + price2, + price3, + minPrice, + workerFk, + isChecked, + isPickedOff, + ektFk, + weight, + deliveryFk, + itemOriginalFk) + SELECT + vToEntryFk, itemFk, - quantity, + vIshStickers * packing, buyingValue, freightValue, isIgnored, - stickers, + vIshStickers, packing, `grouping`, groupingMode, @@ -90,40 +101,17 @@ BEGIN ektFk, weight, deliveryFk, - itemOriginalFk) - SELECT - vToEntryFk, - itemFk, - vIshStickers * packing, - buyingValue, - freightValue, - isIgnored, - vIshStickers, - packing, - `grouping`, - groupingMode, - comissionValue, - packageValue, - location, - packagingFk, - price1, - price2, - price3, - minPrice, - workerFk, - isChecked, - isPickedOff, - ektFk, - weight, - deliveryFk, - itemOriginalFk - FROM vn.buy - WHERE id = vBuyFk; - - UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); - END IF; - END LOOP; - - CLOSE cur; + itemOriginalFk + FROM buy + WHERE id = vBuyFk; + + UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); + END IF; + + UPDATE itemShelving + SET isSplit = TRUE + WHERE shelvingFk = vShelvingFk; + END LOOP; + CLOSE cur; END$$ DELIMITER ; diff --git a/db/versions/11131-brownPhormium/00-firstScript.sql b/db/versions/11131-brownPhormium/00-firstScript.sql new file mode 100644 index 000000000..341c9f1a3 --- /dev/null +++ b/db/versions/11131-brownPhormium/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.itemShelving ADD isSplit tinyint(1) NULL COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda'; \ No newline at end of file From 2278b9a05aa25835ded18b6f2ff784ba5d88ff3f Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 14:20:43 +0200 Subject: [PATCH 10/42] feat: refs #7382 Changes --- .../vn/procedures/invoiceIn_booking.sql | 25 +++++++++++++------ .../11127-silverMoss/00-firstScript.sql | 1 - 2 files changed, 18 insertions(+), 8 deletions(-) delete mode 100644 db/versions/11127-silverMoss/00-firstScript.sql diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index cd838861a..decbb7b1a 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -13,20 +13,31 @@ BEGIN * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo */ DECLARE vFiscalYear INT; - DECLARE vHasDistinctTransactions INT; + DECLARE vDistinctTransactions INT; + DECLARE vHasRepeatedTransactions BOOL; - SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + SELECT COUNT(DISTINCT iit.transactionTypeSageFk) INTO vDistinctTransactions + FROM invoiceInTax iit JOIN invoiceInSerial iis ON iis.code = ii.serial - WHERE ii.id = vSelf + WHERE iit.invoiceInFk = vSelf AND iis.taxAreaFk = 'CEE' - AND transactionTypeSageFk; + AND iit.transactionTypeSageFk; - IF vHasDistinctTransactions > 1 THEN + IF vDistinctTransactions > 1 THEN CALL util.throw ('This invoice does not allow different types of transactions'); END IF; + SELECT TRUE INTO vHasRepeatedTransactions + FROM invoiceInTax + WHERE invoiceInFk = vSelf + GROUP BY transactionTypeSageFk + HAVING COUNT(transactionTypeSageFk) > 1 + LIMIT 1; + + IF vHasRepeatedTransactions THEN + CALL util.throw ('This invoice contains repeated types of transactions'); + END IF; + CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn ENGINE = MEMORY SELECT ii.bookEntried, diff --git a/db/versions/11127-silverMoss/00-firstScript.sql b/db/versions/11127-silverMoss/00-firstScript.sql deleted file mode 100644 index aae2e857e..000000000 --- a/db/versions/11127-silverMoss/00-firstScript.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE vn.invoiceInTax ADD CONSTRAINT invoiceInTax_unique UNIQUE KEY (invoiceInFk,expenseFk); From 246b34571d786f8fbf635038304135629ab16077 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 14:24:26 +0200 Subject: [PATCH 11/42] feat: refs #7382 Fix --- db/routines/vn/procedures/invoiceIn_booking.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index decbb7b1a..c194a774d 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -17,7 +17,8 @@ BEGIN DECLARE vHasRepeatedTransactions BOOL; SELECT COUNT(DISTINCT iit.transactionTypeSageFk) INTO vDistinctTransactions - FROM invoiceInTax iit + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id JOIN invoiceInSerial iis ON iis.code = ii.serial WHERE iit.invoiceInFk = vSelf AND iis.taxAreaFk = 'CEE' From 1ec7cd9540dc3e1d003cbb8d31e3b291383af0fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 16:59:01 +0200 Subject: [PATCH 12/42] Hotfix sale_getProblems --- db/routines/vn/procedures/sale_getProblems.sql | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index 9944ab0c2..f198be54b 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -278,12 +278,11 @@ BEGIN -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra CALL buyUltimate(vWarehouseFk, vDate); INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) - SELECT ticketFk, problem, saleFk + SELECT ticketFk,problem , saleFk FROM ( SELECT tl.ticketFk, - s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, - MOD(s.quantity, b.`grouping`) hasRounding + s.id saleFk, + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk @@ -291,9 +290,9 @@ BEGIN JOIN item i ON i.id = s.itemFk JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk JOIN buy b ON b.id = bu.buyFk + WHERE MOD(s.quantity, b.`grouping`) GROUP BY tl.ticketFk - HAVING hasRounding - ) sub + )sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; CLOSE vCursor; From 097350adb66a233515018f2e8a17b86065fdef54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 17:07:25 +0200 Subject: [PATCH 13/42] Hotfix sale_getProblems --- db/routines/vn/procedures/sale_getProblems.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index f198be54b..ba4ff5857 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -278,11 +278,11 @@ BEGIN -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra CALL buyUltimate(vWarehouseFk, vDate); INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) - SELECT ticketFk,problem , saleFk + SELECT ticketFk, problem ,saleFk FROM ( SELECT tl.ticketFk, s.id saleFk, - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk From d65af6aaaac6c5cb85856d2f44f97bf327b26a43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 18:00:28 +0200 Subject: [PATCH 14/42] feat: Avisar cuando no hay posibilidad de fichar refs #7669 --- .../vn/procedures/workerTimeControl_direction.sql | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/db/routines/vn/procedures/workerTimeControl_direction.sql b/db/routines/vn/procedures/workerTimeControl_direction.sql index f7a68e1e4..807dc46c6 100644 --- a/db/routines/vn/procedures/workerTimeControl_direction.sql +++ b/db/routines/vn/procedures/workerTimeControl_direction.sql @@ -9,6 +9,8 @@ BEGIN */ DECLARE vLastIn DATETIME ; DECLARE vIsMiddleOdd BOOLEAN ; + DECLARE vMailTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; IF (vTimed IS NULL) THEN SET vTimed = util.VN_NOW(); @@ -57,5 +59,18 @@ BEGIN VALUES('in', NULL); END IF; + IF (SELECT option1 IS NULL AND option2 IS NULL FROM tmp.workerTimeControlDirection) THEN + SELECT CONCAT(u.name, '@verdnatura.es'), CONCAT(w.firstName, ' ', w.lastName) + INTO vMailTo, vUserName + FROM account.user u + JOIN worker w ON w.bossFk = u.id + WHERE w.id = vWorkerFk; + + CALL mail_insert( + vMailTo, + vMailTo, + 'Error al fichar', + CONCAT(vUserName, ' tiene problemas para fichar'); + END IF; END$$ DELIMITER ; From 989fa5ac5a3f2b101a38b85413f1552be9c3111f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 18:10:02 +0200 Subject: [PATCH 15/42] feat: Avisar cuando no hay posibilidad de fichar refs #7669 --- db/routines/vn/procedures/workerTimeControl_direction.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/workerTimeControl_direction.sql b/db/routines/vn/procedures/workerTimeControl_direction.sql index 807dc46c6..8e807084c 100644 --- a/db/routines/vn/procedures/workerTimeControl_direction.sql +++ b/db/routines/vn/procedures/workerTimeControl_direction.sql @@ -70,7 +70,7 @@ BEGIN vMailTo, vMailTo, 'Error al fichar', - CONCAT(vUserName, ' tiene problemas para fichar'); + CONCAT(vUserName, ' tiene problemas para fichar')); END IF; END$$ DELIMITER ; From a7b653c42a5f886d8eba1507fff24bcbc8dbdb4d Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 07:34:41 +0200 Subject: [PATCH 16/42] refs #7486 Fix collection_new --- .../vn/procedures/collection_assign.sql | 4 +- db/routines/vn/procedures/collection_get.sql | 45 ++++++++++--------- .../vn/procedures/productionControl.sql | 8 +++- db/routines/vn/procedures/ticket_Clone.sql | 5 +++ 4 files changed, 39 insertions(+), 23 deletions(-) diff --git a/db/routines/vn/procedures/collection_assign.sql b/db/routines/vn/procedures/collection_assign.sql index 84067e7d8..bf130b2c6 100644 --- a/db/routines/vn/procedures/collection_assign.sql +++ b/db/routines/vn/procedures/collection_assign.sql @@ -47,9 +47,9 @@ BEGIN INTO vHasTooMuchCollections, vLockName FROM productionConfig pc - LEFT JOIN tCollection ON TRUE; + LEFT JOIN tmp.collection ON TRUE; - DROP TEMPORARY TABLE tCollection; + DROP TEMPORARY TABLE tmp.collection; IF vHasTooMuchCollections THEN CALL util.throw('Hay colecciones pendientes'); diff --git a/db/routines/vn/procedures/collection_get.sql b/db/routines/vn/procedures/collection_get.sql index 372d963c0..d29f14ca9 100644 --- a/db/routines/vn/procedures/collection_get.sql +++ b/db/routines/vn/procedures/collection_get.sql @@ -7,27 +7,32 @@ BEGIN * @param vWorkerFk id del worker. * @table Devuelve tabla temporal con las colecciones pendientes */ - DROP TEMPORARY TABLE IF EXISTS tCollection; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; - CREATE TEMPORARY TABLE tCollection - SELECT c.id collectionFk, - date(c.created) created, - COUNT(DISTINCT tc.ticketFk) ticketTotalCount - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN sale s ON s.ticketFk = tc.ticketFk - JOIN ticketState ts ON ts.ticketFk = tc.ticketFk - JOIN state s2 ON s2.id = ts.stateFk - JOIN productionConfig pc - JOIN vn.state ss on ss.code = 'PREPARED' - LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vWorkerFk - AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge - AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder - GROUP BY c.id - HAVING COUNT(*) > COUNT(DISTINCT st.id); + CREATE OR REPLACE TEMPORARY TABLE tmp.collection + ENGINE = MEMORY + SELECT c.id collectionFk, + DATE(c.created) created, + COUNT(DISTINCT tc.ticketFk) ticketTotalCount + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN sale s ON s.ticketFk = tc.ticketFk + JOIN ticketState ts ON ts.ticketFk = tc.ticketFk + JOIN state s2 ON s2.id = ts.stateFk + JOIN productionConfig pc + JOIN vn.state ss ON ss.code = 'PREPARED' + LEFT JOIN vn.saleTracking st ON st.saleFk = s.id + AND st.stateFk = ss.id + WHERE c.workerFk = vWorkerFk + AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge + AND s.quantity + AND s2.order < pc.pendingCollectionsOrder + GROUP BY c.id + HAVING COUNT(*) > COUNT(DISTINCT st.id); - SELECT * FROM tCollection; + SELECT * FROM tmp.collection; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index 09c01d1ef..dad46393d 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -15,6 +15,11 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY INTO vEndingDate FROM productionConfig; @@ -31,7 +36,8 @@ proc: BEGIN CALL prepareClientList(); CREATE OR REPLACE TEMPORARY TABLE tmp.sale_getProblems - (INDEX (ticketFk)) ENGINE = MEMORY + (INDEX (ticketFk)) + ENGINE = MEMORY SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped FROM tmp.productionTicket tt JOIN ticket t ON t.id = tt.ticketFk; diff --git a/db/routines/vn/procedures/ticket_Clone.sql b/db/routines/vn/procedures/ticket_Clone.sql index 7670e832e..d22d3c7ff 100644 --- a/db/routines/vn/procedures/ticket_Clone.sql +++ b/db/routines/vn/procedures/ticket_Clone.sql @@ -9,6 +9,11 @@ BEGIN */ DECLARE vStateFk INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + INSERT INTO ticket ( clientFk, shipped, From 897da1e48a70570d6fc172f301b7ac347bc84622 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 4 Jul 2024 08:59:22 +0200 Subject: [PATCH 17/42] feat: refs #7654 --- .../vn/procedures/entry_splitByShelving.sql | 164 +++++++++--------- 1 file changed, 82 insertions(+), 82 deletions(-) diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index 839bf02d1..eb07c12b7 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -9,81 +9,55 @@ BEGIN * @param vToEntryFk Entrada destino */ DECLARE vBuyFk INT; - DECLARE vIshStickers INT; - DECLARE vBuyStickers INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; + DECLARE vIshStickers INT; + DECLARE vBuyStickers INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + + DECLARE cur CURSOR FOR + SELECT bb.id buyFk, + FLOOR(ish.visible / ish.packing) ishStickers, + bb.stickers buyStickers + FROM itemShelving ish + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM buy b + WHERE b.entryFk = vFromEntryFk + ORDER BY b.stickers DESC + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + AND bb.stickers >= FLOOR(ish.visible / ish.packing) + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + AND NOT ish.isSplit + GROUP BY ish.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN cur; + + read_loop: LOOP + SET vDone = FALSE; - DECLARE cur CURSOR FOR - SELECT bb.id buyFk, - FLOOR(ish.visible / ish.packing) ishStickers, - bb.stickers buyStickers - FROM itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM buy b - WHERE b.entryFk = vFromEntryFk - ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - AND bb.stickers >= FLOOR(ish.visible / ish.packing) - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci - AND NOT ish.isSplit - GROUP BY ish.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - OPEN cur; - - read_loop: LOOP - SET vDone = FALSE; - - FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; - - IF vDone THEN - LEAVE read_loop; - END IF; - - IF vIshStickers = vBuyStickers THEN - UPDATE buy - SET entryFk = vToEntryFk - WHERE id = vBuyFk; - ELSE - UPDATE buy - SET stickers = stickers - vIshStickers, - quantity = stickers * packing - WHERE id = vBuyFk; - - INSERT INTO buy(entryFk, - itemFk, - quantity, - buyingValue, - freightValue, - isIgnored, - stickers, - packing, - `grouping`, - groupingMode, - comissionValue, - packageValue, - location, - packagingFk, - price1, - price2, - price3, - minPrice, - workerFk, - isChecked, - isPickedOff, - ektFk, - weight, - deliveryFk, - itemOriginalFk) - SELECT - vToEntryFk, + FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; + + IF vDone THEN + LEAVE read_loop; + END IF; + + IF vIshStickers = vBuyStickers THEN + UPDATE buy + SET entryFk = vToEntryFk + WHERE id = vBuyFk; + ELSE + UPDATE buy + SET stickers = stickers - vIshStickers, + quantity = stickers * packing + WHERE id = vBuyFk; + + INSERT INTO buy(entryFk, itemFk, - vIshStickers * packing, + quantity, buyingValue, freightValue, isIgnored, - vIshStickers, + stickers, packing, `grouping`, groupingMode, @@ -101,17 +75,43 @@ BEGIN ektFk, weight, deliveryFk, - itemOriginalFk - FROM buy - WHERE id = vBuyFk; - - UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); - END IF; - - UPDATE itemShelving - SET isSplit = TRUE - WHERE shelvingFk = vShelvingFk; - END LOOP; - CLOSE cur; + itemOriginalFk) + SELECT + vToEntryFk, + itemFk, + vIshStickers * packing, + buyingValue, + freightValue, + isIgnored, + vIshStickers, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + location, + packagingFk, + price1, + price2, + price3, + minPrice, + workerFk, + isChecked, + isPickedOff, + ektFk, + weight, + deliveryFk, + itemOriginalFk + FROM buy + WHERE id = vBuyFk; + + UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); + END IF; + + UPDATE itemShelving + SET isSplit = TRUE + WHERE shelvingFk = vShelvingFk; + END LOOP; + CLOSE cur; END$$ DELIMITER ; From 009dcd8fc7d3aabf91166752c09dd67749ce8caa Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 09:23:57 +0200 Subject: [PATCH 18/42] refs #7486 Fix tests --- db/dump/.dump/structure.sql | 3404 +++++++++++++++++------------------ 1 file changed, 1702 insertions(+), 1702 deletions(-) diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index cd5b6aa3b..6797c01a5 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -3109,55 +3109,55 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_update`() -BEGIN - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); - - DELETE FROM analisis_ventas - WHERE Año > YEAR(vLastMonth) - OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); - - INSERT INTO analisis_ventas ( - Familia, - Reino, - Comercial, - Comprador, - Provincia, - almacen, - Año, - Mes, - Semana, - Vista, - Importe - ) - SELECT - it.name, - ic.name, - w.code, - w2.code, - p.name, - wa.name, - tm.year, - tm.month, - tm.week, - dm.description, - bt.importe - FROM bs.ventas bt - LEFT JOIN vn.itemType it ON it.id = bt.tipo_id - LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN vn.client c on c.id = bt.Id_Cliente - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.worker w2 ON w2.id = it.workerFk - JOIN vn.time tm ON tm.dated = bt.fecha - JOIN vn.sale s ON s.id = bt.Id_Movimiento - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk - LEFT JOIN vn.address a ON a.id = t.addressFk - LEFT JOIN vn.province p ON p.id = a.provinceFk - LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk - WHERE bt.fecha >= vLastMonth AND ic.merchandise; +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); + + DELETE FROM analisis_ventas + WHERE Año > YEAR(vLastMonth) + OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); + + INSERT INTO analisis_ventas ( + Familia, + Reino, + Comercial, + Comprador, + Provincia, + almacen, + Año, + Mes, + Semana, + Vista, + Importe + ) + SELECT + it.name, + ic.name, + w.code, + w2.code, + p.name, + wa.name, + tm.year, + tm.month, + tm.week, + dm.description, + bt.importe + FROM bs.ventas bt + LEFT JOIN vn.itemType it ON it.id = bt.tipo_id + LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN vn.client c on c.id = bt.Id_Cliente + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.worker w2 ON w2.id = it.workerFk + JOIN vn.time tm ON tm.dated = bt.fecha + JOIN vn.sale s ON s.id = bt.Id_Movimiento + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + LEFT JOIN vn.address a ON a.id = t.addressFk + LEFT JOIN vn.province p ON p.id = a.provinceFk + LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk + WHERE bt.fecha >= vLastMonth AND ic.merchandise; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3355,21 +3355,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE vDateLong DATETIME; - DECLARE vOneYearAgo DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); - SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); - SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); - - DELETE FROM bi.Greuge_Evolution - WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) - OR Fecha < vOneYearAgo; - - DELETE FROM bi.defaulters WHERE `date` < vDateLong; - DELETE FROM bi.defaulting WHERE `date` < vDateLong; +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vDateLong DATETIME; + DECLARE vOneYearAgo DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); + + DELETE FROM bi.Greuge_Evolution + WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) + OR Fecha < vOneYearAgo; + + DELETE FROM bi.defaulters WHERE `date` < vDateLong; + DELETE FROM bi.defaulting WHERE `date` < vDateLong; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3558,18 +3558,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `facturacion_media_anual_update`() -BEGIN - TRUNCATE TABLE bs.clientAnnualConsumption; - - REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) - SELECT clientFk, avg(Facturacion) - FROM ( - SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion - FROM vn.invoiceOut - WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) - GROUP BY clientFk, year, month - ) vol - GROUP BY clientFk; +BEGIN + TRUNCATE TABLE bs.clientAnnualConsumption; + + REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) + SELECT clientFk, avg(Facturacion) + FROM ( + SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion + FROM vn.invoiceOut + WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4934,29 +4934,29 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`() -BEGIN -/** - * Inserta en la tabla @bs.carteras las ventas desde el año pasado - * agrupadas por trabajador, año y mes - */ - DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; - - DELETE FROM bs.carteras WHERE Año >= vYear; - - CALL util.time_generate( - MAKEDATE(vYear, 1), - (SELECT MAX(fecha) FROM ventas) - ); - - INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) - SELECT t.`year`, t.`month`, w.code, SUM(v.importe) - FROM tmp.time t - JOIN ventas v on t.dated = v.fecha - JOIN vn.client c on c.id = v.Id_Cliente - JOIN vn.worker w ON w.id = c.salesPersonFk - GROUP BY w.code, t.`year`, t.`month`; - - DROP TEMPORARY TABLE tmp.time; +BEGIN +/** + * Inserta en la tabla @bs.carteras las ventas desde el año pasado + * agrupadas por trabajador, año y mes + */ + DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; + + DELETE FROM bs.carteras WHERE Año >= vYear; + + CALL util.time_generate( + MAKEDATE(vYear, 1), + (SELECT MAX(fecha) FROM ventas) + ); + + INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) + SELECT t.`year`, t.`month`, w.code, SUM(v.importe) + FROM tmp.time t + JOIN ventas v on t.dated = v.fecha + JOIN vn.client c on c.id = v.Id_Cliente + JOIN vn.worker w ON w.id = c.salesPersonFk + GROUP BY w.code, t.`year`, t.`month`; + + DROP TEMPORARY TABLE tmp.time; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5881,82 +5881,82 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `nightTask_launchAll`() -BEGIN -/** - * Runs all nightly tasks. - */ - DECLARE vDone BOOL; - DECLARE vError VARCHAR(255); - DECLARE vErrorCode VARCHAR(255); - DECLARE vSchema VARCHAR(255); - DECLARE vProcedure VARCHAR(255); - DECLARE vLogMail VARCHAR(255); - DECLARE vNightTaskFk INT; - - DECLARE vQueue CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask - WHERE finished <= util.VN_CURDATE() - OR finished IS NULL - ORDER BY `order`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SET max_sp_recursion_depth = 3; - - SELECT logMail INTO vLogMail - FROM nightTaskConfig LIMIT 1; - - OPEN vQueue; - l: LOOP - SET vDone = FALSE; - FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; - - IF vDone THEN - LEAVE l; - END IF; - - UPDATE nightTask - SET `started` = util.VN_NOW(), - `finished` = NULL, - `error` = NULL, - `errorCode` = NULL - WHERE id = vNightTaskFk; - - SET vError = NULL; - CALL nightTask_launchTask( - vSchema, - vProcedure, - vError, - vErrorCode - ); - - IF vError IS NOT NULL THEN - IF vLogMail IS NOT NULL THEN - CALL vn.mail_insert( - vLogMail, - NULL, - CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), - CONCAT( - '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break - 'See ', SCHEMA(), '.nightTask table for more info.' - ) - ); - END IF; - - UPDATE nightTask - SET `error` = vError, - `errorCode` = vErrorCode - WHERE id = vNightTaskFk; - ELSE - UPDATE nightTask - SET finished = util.VN_NOW(), - lastFinished = util.VN_NOW() - WHERE id = vNightTaskFk; - END IF; - END LOOP; - CLOSE vQueue; +BEGIN +/** + * Runs all nightly tasks. + */ + DECLARE vDone BOOL; + DECLARE vError VARCHAR(255); + DECLARE vErrorCode VARCHAR(255); + DECLARE vSchema VARCHAR(255); + DECLARE vProcedure VARCHAR(255); + DECLARE vLogMail VARCHAR(255); + DECLARE vNightTaskFk INT; + + DECLARE vQueue CURSOR FOR + SELECT id, `schema`, `procedure` + FROM nightTask + WHERE finished <= util.VN_CURDATE() + OR finished IS NULL + ORDER BY `order`; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SET max_sp_recursion_depth = 3; + + SELECT logMail INTO vLogMail + FROM nightTaskConfig LIMIT 1; + + OPEN vQueue; + l: LOOP + SET vDone = FALSE; + FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; + + IF vDone THEN + LEAVE l; + END IF; + + UPDATE nightTask + SET `started` = util.VN_NOW(), + `finished` = NULL, + `error` = NULL, + `errorCode` = NULL + WHERE id = vNightTaskFk; + + SET vError = NULL; + CALL nightTask_launchTask( + vSchema, + vProcedure, + vError, + vErrorCode + ); + + IF vError IS NOT NULL THEN + IF vLogMail IS NOT NULL THEN + CALL vn.mail_insert( + vLogMail, + NULL, + CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), + CONCAT( + '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break + 'See ', SCHEMA(), '.nightTask table for more info.' + ) + ); + END IF; + + UPDATE nightTask + SET `error` = vError, + `errorCode` = vErrorCode + WHERE id = vNightTaskFk; + ELSE + UPDATE nightTask + SET finished = util.VN_NOW(), + lastFinished = util.VN_NOW() + WHERE id = vNightTaskFk; + END IF; + END LOOP; + CLOSE vQueue; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6336,8 +6336,8 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_addLauncher`() -BEGIN - CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); +BEGIN + CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7589,27 +7589,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7627,89 +7627,89 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - DECLARE vLastRefresh DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires, ca.last_refresh - INTO v_cache_id, v_calc, v_expires, vLastRefresh - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + DECLARE vLastRefresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires, ca.last_refresh + INTO v_cache_id, v_calc, v_expires, vLastRefresh + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10228,524 +10228,524 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`() -proc: BEGIN - DECLARE vLanded DATETIME; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vFreeId INT; - DECLARE vSupplyResponseFk INT; - DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; - DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; - DECLARE vDayRange INT; - - DECLARE cur1 CURSOR FOR - SELECT id - FROM edi.item_free; - - DECLARE cur2 CURSOR FOR - SELECT srId - FROM itemToInsert; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); - SET @isTriggerDisabled = FALSE; - RESIGNAL; - END; - - IF 'test' = (SELECT environment FROM util.config) THEN - LEAVE proc; - END IF; - - IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN - LEAVE proc; - END IF; - - SELECT dayRange INTO vDayRange - FROM offerRefreshConfig; - - IF vDayRange IS NULL THEN - CALL util.throw("Variable vDayRange not declared"); - END IF; - - SET vStartingTime = util.VN_NOW(); - - TRUNCATE edi.offerList; - - INSERT INTO edi.offerList(supplier, total) - SELECT v.name, COUNT(DISTINCT sr.ID) total - FROM edi.supplyResponse sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - WHERE sr.NumberOfUnits > 0 - AND sr.EmbalageCode != 999 - GROUP BY sr.vmpID; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(*) total - FROM edi.supplyOffer sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.`filter` = sub.total; - - -- Elimina de la lista de items libres aquellos que ya existen - DELETE itf.* - FROM edi.item_free itf - JOIN vn.item i ON i.id = itf.id; - - CREATE OR REPLACE TEMPORARY TABLE tmp - (INDEX (`Item_ArticleCode`)) - ENGINE = MEMORY - SELECT t.* - FROM ( - SELECT * - FROM edi.supplyOffer - ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, - NumberOfUnits DESC LIMIT 10000000000000000000) t - GROUP BY t.srId; - - CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), - INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), - INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) - ENGINE = MEMORY - SELECT so.*, - ev1.type_description s1Value, - ev2.type_description s2Value, - ev3.type_description s3Value, - ev4.type_description s4Value, - ev5.type_description s5Value, - ev6.type_description s6Value, - eif1.feature ef1, - eif2.feature ef2, - eif3.feature ef3, - eif4.feature ef4, - eif5.feature ef5, - eif6.feature ef6 - FROM tmp so - LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode - AND eif1.presentation_order = 1 - AND eif1.expiry_date IS NULL - LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode - AND eif2.presentation_order = 2 - AND eif2.expiry_date IS NULL - LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode - AND eif3.presentation_order = 3 - AND eif3.expiry_date IS NULL - LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode - AND eif4.presentation_order = 4 - AND eif4.expiry_date IS NULL - LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode - AND eif5.presentation_order = 5 - AND eif5.expiry_date IS NULL - LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode - AND eif6.presentation_order = 6 - AND eif6.expiry_date IS NULL - LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature - AND so.s1 = ev1.type_value - LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature - AND so.s2 = ev2.type_value - LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature - AND so.s3 = ev3.type_value - LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature - AND so.s4 = ev4.type_value - LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature - AND so.s5 = ev5.type_value - LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature - AND so.s6 = ev6.type_value - ORDER BY Price; - - DROP TEMPORARY TABLE tmp; - - DELETE o - FROM edi.offer o - LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' - LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' - LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' - LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' - LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' - LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' - JOIN vn.floramondoConfig fc ON TRUE - WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) - OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) - OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) - OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) - OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) - OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); - - START TRANSACTION; - - -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos - UPDATE IGNORE edi.offer o - JOIN vn.item i - ON i.name = o.product_name - AND i.subname <=> o.company_name - AND i.value5 <=> o.s1Value - AND i.value6 <=> o.s2Value - AND i.value7 <=> o.s3Value - AND i.value8 <=> o.s4Value - AND i.value9 <=> o.s5Value - AND i.value10 <=> o.s6Value - AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask - AND i.EmbalageCode <=> o.EmbalageCode - AND i.quality <=> o.Quality - JOIN vn.itemType it ON it.id = i.typeFk - LEFT JOIN vn.sale s ON s.itemFk = i.id - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) - LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk - AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) - SET i.supplyResponseFk = o.srID - WHERE (sr.ID IS NULL - OR sr.NumberOfUnits = 0 - OR di.LatestOrderDateTime < util.VN_NOW() - OR di.ID IS NULL) - AND it.isInventory - AND t.id IS NULL - AND po.id IS NULL; - - CREATE OR REPLACE TEMPORARY TABLE itemToInsert - ENGINE = MEMORY - SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk - FROM edi.offer o - LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId - WHERE i.id IS NULL - LIMIT vMaxNewItems; - - -- Reciclado de nº de item - OPEN cur1; - OPEN cur2; - - read_loop: LOOP - - FETCH cur2 INTO vSupplyResponseFk; - FETCH cur1 INTO vFreeId; - - IF vDone THEN - LEAVE read_loop; - END IF; - - UPDATE itemToInsert - SET itemFk = vFreeId - WHERE srId = vSupplyResponseFk; - - END LOOP; - - CLOSE cur1; - CLOSE cur2; - - -- Insertamos todos los items en Articles de la oferta - INSERT INTO vn.item(id, - `name`, - longName, - subName, - expenseFk, - typeFk, - intrastatFk, - originFk, - supplyResponseFk, - numberOfItemsPerCask, - embalageCode, - quality, - isFloramondo) - SELECT iti.itemFk, - iti.product_name, - iti.product_name, - iti.company_name, - iti.expenseFk, - iti.itemTypeFk, - iti.intrastatFk, - iti.originFk, - iti.`srId`, - iti.NumberOfItemsPerCask, - iti.EmbalageCode, - iti.Quality, - TRUE - FROM itemToInsert iti; - - -- Inserta la foto de los articulos nuevos (prioridad alta) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) - SELECT i.id, PictureReference - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.srId - WHERE PictureReference IS NOT NULL - AND i.image IS NULL; - - INSERT INTO edi.`log`(tableName, fieldName,fieldValue) - SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) - FROM vn.itemImageQueue - WHERE attempts = 0; - - -- Inserta si se añadiesen tags nuevos - INSERT IGNORE INTO vn.tag (name, ediTypeFk) - SELECT description, type_id FROM edi.type; - - -- Desabilita el trigger para recalcular los tags al final - SET @isTriggerDisabled = TRUE; - - -- Inserta los tags sólo en los articulos nuevos - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.product_name, 1 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Producto' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.product_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.Quality, 3 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Calidad' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.Quality IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.company_name, 4 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Productor' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.company_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s1Value, 5 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef1 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s1Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s2Value, 6 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef2 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s2Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s3Value, 7 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef3 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s3Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s4Value, 8 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef4 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s4Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s5Value, 9 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef5 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s5Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s6Value, 10 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef6 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s6Value IS NULL; - - INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode - LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id - AND tp.`description` = 'Hoofdkleur 1' - LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value - LEFT JOIN vn.itemInk ik ON ik.longName = i.longName - WHERE ink.name IS NOT NULL - OR ik.color IS NOT NULL; - - CREATE OR REPLACE TABLE tmp.item - (PRIMARY KEY (id)) - SELECT i.id FROM vn.item i - JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; - - CALL vn.item_refreshTags(); - - DROP TABLE tmp.item; - - SELECT MIN(LatestDeliveryDateTime) INTO vLanded - FROM edi.supplyResponse sr - JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.floramondoConfig fc - WHERE mp.isLatestOrderDateTimeRelevant - AND di.LatestOrderDateTime > IF( - fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), - util.VN_CURDATE(), - util.VN_CURDATE() + INTERVAL 1 DAY); - - UPDATE vn.floramondoConfig - SET nextLanded = vLanded - WHERE vLanded IS NOT NULL; - - -- Elimina la oferta obsoleta - UPDATE vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID - LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk - SET b.quantity = 0 - WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() - OR i.supplyResponseFk IS NULL - OR sr.NumberOfUnits = 0) - AND am.name = 'LOGIFLORA' - AND e.isRaid; - - -- Localiza las entradas de cada almacen - UPDATE edi.warehouseFloramondo - SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); - - IF vLanded IS NOT NULL THEN - -- Actualiza la oferta existente - UPDATE vn.buy b - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.offer o ON i.supplyResponseFk = o.`srId` - SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, - b.buyingValue = o.price - WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask - OR b.buyingValue <> o.price); - - -- Inserta el resto - SET vLastInserted := util.VN_NOW(); - - -- Inserta la oferta - INSERT INTO vn.buy ( - entryFk, - itemFk, - quantity, - buyingValue, - stickers, - packing, - `grouping`, - groupingMode, - packagingFk, - deliveryFk) - SELECT wf.entryFk, - i.id, - o.NumberOfUnits * o.NumberOfItemsPerCask quantity, - o.Price, - o.NumberOfUnits etiquetas, - o.NumberOfItemsPerCask packing, - GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, - 'packing', - o.embalageCode, - o.diId - FROM edi.offer o - JOIN vn.item i ON i.supplyResponseFk = o.srId - JOIN edi.warehouseFloramondo wf - JOIN vn.packaging p ON p.id - LIKE o.embalageCode - LEFT JOIN vn.buy b ON b.itemFk = i.id - AND b.entryFk = wf.entryFk - WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL - - INSERT INTO vn.itemCost( - itemFk, - warehouseFk, - cm3, - cm3delivery) - SELECT b.itemFk, - wf.warehouseFk, - @cm3 := vn.buy_getUnitVolume(b.id), - IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) - FROM warehouseFloramondo wf - JOIN vn.volumeConfig vc - JOIN vn.buy b ON b.entryFk = wf.entryFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk - AND ic.warehouseFk = wf.warehouseFk - WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) - ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); - - CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc - SELECT b.id - FROM vn.buy b - JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk - WHERE b.created >= vLastInserted; - - CALL vn.buy_recalcPrices(); - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'VNH' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.vnh = sub.total; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'ALGEMESI' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.algemesi = sub.total; - END IF; - - DROP TEMPORARY TABLE - edi.offer, - itemToInsert; - - SET @isTriggerDisabled = FALSE; - - COMMIT; - - -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias - UPDATE vn.item i - SET typeFk = 121 - WHERE i.longName LIKE 'Rosa Garden %' - AND typeFk = 17; - - UPDATE vn.item i - SET typeFk = 156 - WHERE i.longName LIKE 'Rosa ec %' - AND typeFk = 17; - - -- Refresca las fotos de los items existentes que mostramos (prioridad baja) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) - SELECT i.id, sr.PictureReference, 100 - FROM edi.supplyResponse sr - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN edi.supplyOffer so ON so.srId = sr.ID - JOIN hedera.image i2 ON i2.name = i.image - AND i2.collectionFk = 'catalog' - WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) - AND sr.NumberOfUnits; - - INSERT INTO edi.`log` - SET tableName = 'floramondo_offerRefresh', - fieldName = 'Tiempo de proceso', - fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); - - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); +proc: BEGIN + DECLARE vLanded DATETIME; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vFreeId INT; + DECLARE vSupplyResponseFk INT; + DECLARE vLastInserted DATETIME; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vStartingTime DATETIME; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + DECLARE vDayRange INT; + + DECLARE cur1 CURSOR FOR + SELECT id + FROM edi.item_free; + + DECLARE cur2 CURSOR FOR + SELECT srId + FROM itemToInsert; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); + SET @isTriggerDisabled = FALSE; + RESIGNAL; + END; + + IF 'test' = (SELECT environment FROM util.config) THEN + LEAVE proc; + END IF; + + IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN + LEAVE proc; + END IF; + + SELECT dayRange INTO vDayRange + FROM offerRefreshConfig; + + IF vDayRange IS NULL THEN + CALL util.throw("Variable vDayRange not declared"); + END IF; + + SET vStartingTime = util.VN_NOW(); + + TRUNCATE edi.offerList; + + INSERT INTO edi.offerList(supplier, total) + SELECT v.name, COUNT(DISTINCT sr.ID) total + FROM edi.supplyResponse sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + WHERE sr.NumberOfUnits > 0 + AND sr.EmbalageCode != 999 + GROUP BY sr.vmpID; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(*) total + FROM edi.supplyOffer sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.`filter` = sub.total; + + -- Elimina de la lista de items libres aquellos que ya existen + DELETE itf.* + FROM edi.item_free itf + JOIN vn.item i ON i.id = itf.id; + + CREATE OR REPLACE TEMPORARY TABLE tmp + (INDEX (`Item_ArticleCode`)) + ENGINE = MEMORY + SELECT t.* + FROM ( + SELECT * + FROM edi.supplyOffer + ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, + NumberOfUnits DESC LIMIT 10000000000000000000) t + GROUP BY t.srId; + + CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), + INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), + INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) + ENGINE = MEMORY + SELECT so.*, + ev1.type_description s1Value, + ev2.type_description s2Value, + ev3.type_description s3Value, + ev4.type_description s4Value, + ev5.type_description s5Value, + ev6.type_description s6Value, + eif1.feature ef1, + eif2.feature ef2, + eif3.feature ef3, + eif4.feature ef4, + eif5.feature ef5, + eif6.feature ef6 + FROM tmp so + LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode + AND eif1.presentation_order = 1 + AND eif1.expiry_date IS NULL + LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode + AND eif2.presentation_order = 2 + AND eif2.expiry_date IS NULL + LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode + AND eif3.presentation_order = 3 + AND eif3.expiry_date IS NULL + LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode + AND eif4.presentation_order = 4 + AND eif4.expiry_date IS NULL + LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode + AND eif5.presentation_order = 5 + AND eif5.expiry_date IS NULL + LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode + AND eif6.presentation_order = 6 + AND eif6.expiry_date IS NULL + LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature + AND so.s1 = ev1.type_value + LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature + AND so.s2 = ev2.type_value + LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature + AND so.s3 = ev3.type_value + LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature + AND so.s4 = ev4.type_value + LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature + AND so.s5 = ev5.type_value + LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature + AND so.s6 = ev6.type_value + ORDER BY Price; + + DROP TEMPORARY TABLE tmp; + + DELETE o + FROM edi.offer o + LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' + LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' + LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' + LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' + LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' + LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' + JOIN vn.floramondoConfig fc ON TRUE + WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) + OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) + OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) + OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) + OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) + OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); + + START TRANSACTION; + + -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos + UPDATE IGNORE edi.offer o + JOIN vn.item i + ON i.name = o.product_name + AND i.subname <=> o.company_name + AND i.value5 <=> o.s1Value + AND i.value6 <=> o.s2Value + AND i.value7 <=> o.s3Value + AND i.value8 <=> o.s4Value + AND i.value9 <=> o.s5Value + AND i.value10 <=> o.s6Value + AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask + AND i.EmbalageCode <=> o.EmbalageCode + AND i.quality <=> o.Quality + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN vn.sale s ON s.itemFk = i.id + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) + LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk + AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) + SET i.supplyResponseFk = o.srID + WHERE (sr.ID IS NULL + OR sr.NumberOfUnits = 0 + OR di.LatestOrderDateTime < util.VN_NOW() + OR di.ID IS NULL) + AND it.isInventory + AND t.id IS NULL + AND po.id IS NULL; + + CREATE OR REPLACE TEMPORARY TABLE itemToInsert + ENGINE = MEMORY + SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk + FROM edi.offer o + LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId + WHERE i.id IS NULL + LIMIT vMaxNewItems; + + -- Reciclado de nº de item + OPEN cur1; + OPEN cur2; + + read_loop: LOOP + + FETCH cur2 INTO vSupplyResponseFk; + FETCH cur1 INTO vFreeId; + + IF vDone THEN + LEAVE read_loop; + END IF; + + UPDATE itemToInsert + SET itemFk = vFreeId + WHERE srId = vSupplyResponseFk; + + END LOOP; + + CLOSE cur1; + CLOSE cur2; + + -- Insertamos todos los items en Articles de la oferta + INSERT INTO vn.item(id, + `name`, + longName, + subName, + expenseFk, + typeFk, + intrastatFk, + originFk, + supplyResponseFk, + numberOfItemsPerCask, + embalageCode, + quality, + isFloramondo) + SELECT iti.itemFk, + iti.product_name, + iti.product_name, + iti.company_name, + iti.expenseFk, + iti.itemTypeFk, + iti.intrastatFk, + iti.originFk, + iti.`srId`, + iti.NumberOfItemsPerCask, + iti.EmbalageCode, + iti.Quality, + TRUE + FROM itemToInsert iti; + + -- Inserta la foto de los articulos nuevos (prioridad alta) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) + SELECT i.id, PictureReference + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.srId + WHERE PictureReference IS NOT NULL + AND i.image IS NULL; + + INSERT INTO edi.`log`(tableName, fieldName,fieldValue) + SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) + FROM vn.itemImageQueue + WHERE attempts = 0; + + -- Inserta si se añadiesen tags nuevos + INSERT IGNORE INTO vn.tag (name, ediTypeFk) + SELECT description, type_id FROM edi.type; + + -- Desabilita el trigger para recalcular los tags al final + SET @isTriggerDisabled = TRUE; + + -- Inserta los tags sólo en los articulos nuevos + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.product_name, 1 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Producto' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.product_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.Quality, 3 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Calidad' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.Quality IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.company_name, 4 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Productor' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.company_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s1Value, 5 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef1 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s1Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s2Value, 6 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef2 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s2Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s3Value, 7 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef3 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s3Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s4Value, 8 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef4 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s4Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s5Value, 9 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef5 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s5Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s6Value, 10 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef6 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s6Value IS NULL; + + INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + JOIN vn.tag t ON t.`name` = 'Color' + LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode + LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id + AND tp.`description` = 'Hoofdkleur 1' + LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value + LEFT JOIN vn.itemInk ik ON ik.longName = i.longName + WHERE ink.name IS NOT NULL + OR ik.color IS NOT NULL; + + CREATE OR REPLACE TABLE tmp.item + (PRIMARY KEY (id)) + SELECT i.id FROM vn.item i + JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; + + CALL vn.item_refreshTags(); + + DROP TABLE tmp.item; + + SELECT MIN(LatestDeliveryDateTime) INTO vLanded + FROM edi.supplyResponse sr + JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.floramondoConfig fc + WHERE mp.isLatestOrderDateTimeRelevant + AND di.LatestOrderDateTime > IF( + fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), + util.VN_CURDATE(), + util.VN_CURDATE() + INTERVAL 1 DAY); + + UPDATE vn.floramondoConfig + SET nextLanded = vLanded + WHERE vLanded IS NOT NULL; + + -- Elimina la oferta obsoleta + UPDATE vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID + LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk + SET b.quantity = 0 + WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() + OR i.supplyResponseFk IS NULL + OR sr.NumberOfUnits = 0) + AND am.name = 'LOGIFLORA' + AND e.isRaid; + + -- Localiza las entradas de cada almacen + UPDATE edi.warehouseFloramondo + SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); + + IF vLanded IS NOT NULL THEN + -- Actualiza la oferta existente + UPDATE vn.buy b + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.offer o ON i.supplyResponseFk = o.`srId` + SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, + b.buyingValue = o.price + WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask + OR b.buyingValue <> o.price); + + -- Inserta el resto + SET vLastInserted := util.VN_NOW(); + + -- Inserta la oferta + INSERT INTO vn.buy ( + entryFk, + itemFk, + quantity, + buyingValue, + stickers, + packing, + `grouping`, + groupingMode, + packagingFk, + deliveryFk) + SELECT wf.entryFk, + i.id, + o.NumberOfUnits * o.NumberOfItemsPerCask quantity, + o.Price, + o.NumberOfUnits etiquetas, + o.NumberOfItemsPerCask packing, + GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, + 'packing', + o.embalageCode, + o.diId + FROM edi.offer o + JOIN vn.item i ON i.supplyResponseFk = o.srId + JOIN edi.warehouseFloramondo wf + JOIN vn.packaging p ON p.id + LIKE o.embalageCode + LEFT JOIN vn.buy b ON b.itemFk = i.id + AND b.entryFk = wf.entryFk + WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL + + INSERT INTO vn.itemCost( + itemFk, + warehouseFk, + cm3, + cm3delivery) + SELECT b.itemFk, + wf.warehouseFk, + @cm3 := vn.buy_getUnitVolume(b.id), + IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) + FROM warehouseFloramondo wf + JOIN vn.volumeConfig vc + JOIN vn.buy b ON b.entryFk = wf.entryFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk + AND ic.warehouseFk = wf.warehouseFk + WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) + ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); + + CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc + SELECT b.id + FROM vn.buy b + JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk + WHERE b.created >= vLastInserted; + + CALL vn.buy_recalcPrices(); + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'VNH' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.vnh = sub.total; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'ALGEMESI' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.algemesi = sub.total; + END IF; + + DROP TEMPORARY TABLE + edi.offer, + itemToInsert; + + SET @isTriggerDisabled = FALSE; + + COMMIT; + + -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias + UPDATE vn.item i + SET typeFk = 121 + WHERE i.longName LIKE 'Rosa Garden %' + AND typeFk = 17; + + UPDATE vn.item i + SET typeFk = 156 + WHERE i.longName LIKE 'Rosa ec %' + AND typeFk = 17; + + -- Refresca las fotos de los items existentes que mostramos (prioridad baja) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) + SELECT i.id, sr.PictureReference, 100 + FROM edi.supplyResponse sr + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN edi.supplyOffer so ON so.srId = sr.ID + JOIN hedera.image i2 ON i2.name = i.image + AND i2.collectionFk = 'catalog' + WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) + AND sr.NumberOfUnits; + + INSERT INTO edi.`log` + SET tableName = 'floramondo_offerRefresh', + fieldName = 'Tiempo de proceso', + fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); + + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11324,28 +11324,28 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( - vName VARCHAR(100), - vPhone VARCHAR(15), - vEmail VARCHAR(100), +CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( + vName VARCHAR(100), + vPhone VARCHAR(15), + vEmail VARCHAR(100), vMessage TEXT) READS SQL DATA -BEGIN -/** - * Set actions for contact request - * - * @param vName Name - * @param vPhone Phone number - * @param vEmail e-mail - * @param vMessage text of the message - */ - - CALL vn.mail_insert( - 'floranet@verdnatura.es', - vEmail, - 'Contact request', - CONCAT('Phone: ',vPhone, ' Message: ', vMessage) - ); +BEGIN +/** + * Set actions for contact request + * + * @param vName Name + * @param vPhone Phone number + * @param vEmail e-mail + * @param vMessage text of the message + */ + + CALL vn.mail_insert( + 'floranet@verdnatura.es', + vEmail, + 'Contact request', + CONCAT('Phone: ',vPhone, ' Message: ', vMessage) + ); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11364,27 +11364,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryDate_get`(vPostalCode VARCHAR(15)) READS SQL DATA -BEGIN -/** - * Returns available dates for this postalCode, in the next seven days. - * - * @param vPostalCode Delivery address postal code - */ - DECLARE vCurrentDayOfWeek INT; - - SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); - - SELECT DISTINCT nextDay - FROM ( - SELECT CURDATE() + INTERVAL IF( - apc.dayOfWeek >= vCurrentDayOfWeek, - apc.dayOfWeek - vCurrentDayOfWeek, - 7 - apc.dayOfWeek - ) DAY nextDay, - NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime - FROM addressPostCode apc - WHERE apc.postCode = vPostalCode - HAVING nextDay > minDeliveryTime) sub; +BEGIN +/** + * Returns available dates for this postalCode, in the next seven days. + * + * @param vPostalCode Delivery address postal code + */ + DECLARE vCurrentDayOfWeek INT; + + SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); + + SELECT DISTINCT nextDay + FROM ( + SELECT CURDATE() + INTERVAL IF( + apc.dayOfWeek >= vCurrentDayOfWeek, + apc.dayOfWeek - vCurrentDayOfWeek, + 7 - apc.dayOfWeek + ) DAY nextDay, + NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime + FROM addressPostCode apc + WHERE apc.postCode = vPostalCode + HAVING nextDay > minDeliveryTime) sub; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -41995,9 +41995,9 @@ DELIMITER ;; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN - DELETE FROM itemImageQueue - WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN + DELETE FROM itemImageQueue + WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -42689,37 +42689,37 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `client_getDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2) READS SQL DATA -BEGIN -/** - * Returns the risk of a customer. - * - * @param vClient client id - * @param vDate date to check the risk - * @return Client risk - */ - DECLARE vDebt DECIMAL(10,2); - DECLARE vHasDebt BOOLEAN; - - SELECT COUNT(*) INTO vHasDebt - FROM `client` c - WHERE c.id = vClient AND c.typeFk = 'normal'; - - IF NOT vHasDebt THEN - RETURN 0; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); - INSERT INTO tmp.clientGetDebt SET clientFk = vClient; - - CALL vn.client_getDebt(vDate); - - SELECT risk INTO vDebt FROM tmp.risk; - - DROP TEMPORARY TABLE - tmp.clientGetDebt, - tmp.risk; - - RETURN vDebt; +BEGIN +/** + * Returns the risk of a customer. + * + * @param vClient client id + * @param vDate date to check the risk + * @return Client risk + */ + DECLARE vDebt DECIMAL(10,2); + DECLARE vHasDebt BOOLEAN; + + SELECT COUNT(*) INTO vHasDebt + FROM `client` c + WHERE c.id = vClient AND c.typeFk = 'normal'; + + IF NOT vHasDebt THEN + RETURN 0; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); + INSERT INTO tmp.clientGetDebt SET clientFk = vClient; + + CALL vn.client_getDebt(vDate); + + SELECT risk INTO vDebt FROM tmp.risk; + + DROP TEMPORARY TABLE + tmp.clientGetDebt, + tmp.risk; + + RETURN vDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43744,8 +43744,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `getInventoryDate`() RETURNS date DETERMINISTIC -BEGIN - RETURN (SELECT inventoried FROM config LIMIT 1); +BEGIN + RETURN (SELECT inventoried FROM config LIMIT 1); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51378,82 +51378,82 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`( - vUserFk INT, - OUT vCollectionFk INT +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`( + vUserFk INT, + OUT vCollectionFk INT ) -BEGIN -/** - * Comprueba si existen colecciones libres que se ajustan - * al perfil del usuario y le asigna la más antigua. - * Añade un registro al semillero de colecciones. - * - * @param vUserFk Id de usuario - * @param vCollectionFk Id de colección - */ - DECLARE vHasTooMuchCollections BOOL; - - -- Si hay colecciones sin terminar, sale del proceso - CALL collection_get(vUserFk); - - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 - INTO vHasTooMuchCollections - FROM productionConfig pc - LEFT JOIN tCollection ON TRUE; - - DROP TEMPORARY TABLE tCollection; - - IF vHasTooMuchCollections THEN - CALL util.throw('Hay colecciones pendientes'); - END IF; - - -- Se eliminan las colecciones sin asignar que estan obsoletas - INSERT INTO ticketTracking(stateFk, ticketFk) - SELECT s.id, tc.ticketFk - FROM `collection` c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN `state` s ON s.code = 'PRINTED_AUTO' - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - DELETE c.* - FROM `collection` c - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - -- Se añade registro al semillero - INSERT INTO collectionHotbed(userFk) - VALUES(vUserFk); - - -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - SELECT MIN(c.id) INTO vCollectionFk - FROM `collection` c - JOIN operator o - ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk - AND c.workerFk IS NULL - AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) - JOIN ( - SELECT tc.collectionFk, SUM(sv.volume) volume - FROM ticketCollection tc - JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk - WHERE sv.shipped >= util.VN_CURDATE() - GROUP BY tc.collectionFk - ) sub ON sub.collectionFk = c.id - AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) - WHERE o.workerFk = vUserFk; - - IF vCollectionFk IS NULL THEN - CALL collection_new(vUserFk, vCollectionFk); - END IF; - - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; +BEGIN +/** + * Comprueba si existen colecciones libres que se ajustan + * al perfil del usuario y le asigna la más antigua. + * Añade un registro al semillero de colecciones. + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + + -- Si hay colecciones sin terminar, sale del proceso + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 + INTO vHasTooMuchCollections + FROM productionConfig pc + LEFT JOIN tmp.collection ON TRUE; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('Hay colecciones pendientes'); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM `collection` c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN `state` s ON s.code = 'PRINTED_AUTO' + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + DELETE c.* + FROM `collection` c + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + INSERT INTO collectionHotbed(userFk) + VALUES(vUserFk); + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + SELECT MIN(c.id) INTO vCollectionFk + FROM `collection` c + JOIN operator o + ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk + AND c.workerFk IS NULL + AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) + JOIN ( + SELECT tc.collectionFk, SUM(sv.volume) volume + FROM ticketCollection tc + JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk + WHERE sv.shipped >= util.VN_CURDATE() + GROUP BY tc.collectionFk + ) sub ON sub.collectionFk = c.id + AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) + WHERE o.workerFk = vUserFk; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + END IF; + + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51478,9 +51478,9 @@ BEGIN * @param vWorkerFk id del worker. * @table Devuelve tabla temporal con las colecciones pendientes */ - DROP TEMPORARY TABLE IF EXISTS tCollection; + DROP TEMPORARY TABLE IF EXISTS tmp.collection; - CREATE TEMPORARY TABLE tCollection + CREATE TEMPORARY TABLE tmp.collection SELECT c.id collectionFk, date(c.created) created, COUNT(DISTINCT tc.ticketFk) ticketTotalCount @@ -51499,7 +51499,7 @@ BEGIN GROUP BY c.id HAVING COUNT(*) > COUNT(DISTINCT st.id); - SELECT * FROM tCollection; + SELECT * FROM tmp.collection; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60631,167 +60631,167 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) -BEGIN - - /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. - * - * @param vShelvingFk Matrícula del carro o pallet - */ - - DECLARE vWarehouseFk INT; - DECLARE vStockScopeDays INT; - - SELECT s.warehouseFk, stockScopeDays - INTO vWarehouseFk, vStockScopeDays - FROM sector s - JOIN operator o ON s.id = o.sectorFk - JOIN productionConfig pc - WHERE o.workerFk = account.myUser_getId(); - - IF vWarehouseFk IS NULL - THEN CALL util.throw('WarehouseFk not setted'); - END IF; - - IF vStockScopeDays IS NULL - THEN CALL util.throw('StockScopeDays not setted'); - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tItems - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT itemFk, SUM(visible) visible - FROM itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay - (INDEX (itemFk, dated)) - ENGINE = MEMORY - SELECT dated, - SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, - t3.itemFk - FROM ( - SELECT t.itemFk, dated, SUM(amount) amount - FROM ( - SELECT t2.itemFk, t2.amount, t2.dated - FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock s - JOIN tmp.tItems i ON i.itemFk = s.item_id - WHERE s.warehouse_id = vWarehouseFk - UNION ALL - SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() - FROM itemShelving ish - JOIN tmp.tItems i ON i.itemFk = ish.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id - JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve - GROUP BY ish.itemFk - UNION ALL - SELECT iei.itemFk, SUM(quantity), landed - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND iei.warehouseInFk = vWarehouseFk - AND NOT isVirtualStock - GROUP BY iei.itemFk, iei.landed - UNION ALL - SELECT ieo.itemFk, SUM(quantity), shipped - FROM itemEntryOut ieo - JOIN tmp.tItems i ON i.itemFk = ieo.itemFk - WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ieo.warehouseOutFk = vWarehouseFk - GROUP BY ieo.itemFk, ieo.shipped - UNION ALL - SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) - FROM itemTicketOut ito - JOIN tmp.tItems i ON i.itemFk = ito.itemFk - WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ito.warehouseFk = vWarehouseFk - GROUP BY ito.itemFk, ito.shipped - ) t2 - JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t - GROUP BY t.itemFk, dated - ) t3; - - -- Se restan las entradas de hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed = util.VN_CURDATE() - AND iei.warehouseInFk = vWarehouseFk - AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock - sub.todayEntry - WHERE sbd.dated = util.VN_CURDATE(); - - -- Se añaden las lineas de venta servidas - UPDATE tmp.tStockByDay sbd - JOIN (SELECT s.itemFK, SUM(quantity) amount - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - WHERE t.warehouseFk = vWarehouseFk - AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() - AND s.isPicked - GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - -- Se añaden los items ubicados hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT ish.itemFK, SUM(ish.visible) amount - FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector s ON s.id = p.sectorFk - WHERE s.warehouseFk = vWarehouseFk - AND NOT s.isReserve - AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() - GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - SELECT ts.itemFk, - i.longName, - IF(ts.stock<=0, ts.dated, NULL) dated, - ts.stock, - sub4.visible, - sub4.shelvingFk - FROM( - SELECT IFNULL(sub2.minDated, sub.minDated) dated, - IFNULL(sub2.itemFk, sub.itemFk) itemFk - FROM(SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - GROUP BY itemFk)sub - LEFT JOIN ( - SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - WHERE sbd.stock <= 0 - GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk - WHERE sub2.itemFk IS NOT NULL - OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 - LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated - JOIN (SELECT ish.itemFk, - ish.visible, - p.sectorFk, - ish.shelvingFk - FROM itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - LEFT JOIN parking p ON p.id = parkingFk - LEFT JOIN vn.sector s ON s.id = p.sectorFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - ) sub4 ON sub4.itemFk = ts.itemFk - LEFT JOIN sector s ON s.id = sub4.sectorFk - LEFT JOIN item i ON i.id = ts.itemFk - WHERE NOT s.isReserve; - - DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; - +BEGIN + + /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. + * + * @param vShelvingFk Matrícula del carro o pallet + */ + + DECLARE vWarehouseFk INT; + DECLARE vStockScopeDays INT; + + SELECT s.warehouseFk, stockScopeDays + INTO vWarehouseFk, vStockScopeDays + FROM sector s + JOIN operator o ON s.id = o.sectorFk + JOIN productionConfig pc + WHERE o.workerFk = account.myUser_getId(); + + IF vWarehouseFk IS NULL + THEN CALL util.throw('WarehouseFk not setted'); + END IF; + + IF vStockScopeDays IS NULL + THEN CALL util.throw('StockScopeDays not setted'); + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tItems + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(visible) visible + FROM itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + GROUP BY itemFk; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay + (INDEX (itemFk, dated)) + ENGINE = MEMORY + SELECT dated, + SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, + t3.itemFk + FROM ( + SELECT t.itemFk, dated, SUM(amount) amount + FROM ( + SELECT t2.itemFk, t2.amount, t2.dated + FROM ( + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock s + JOIN tmp.tItems i ON i.itemFk = s.item_id + WHERE s.warehouse_id = vWarehouseFk + UNION ALL + SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() + FROM itemShelving ish + JOIN tmp.tItems i ON i.itemFk = ish.itemFk + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id + JOIN sector s ON s.id = p.sectorFk + WHERE s.isReserve + GROUP BY ish.itemFk + UNION ALL + SELECT iei.itemFk, SUM(quantity), landed + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND iei.warehouseInFk = vWarehouseFk + AND NOT isVirtualStock + GROUP BY iei.itemFk, iei.landed + UNION ALL + SELECT ieo.itemFk, SUM(quantity), shipped + FROM itemEntryOut ieo + JOIN tmp.tItems i ON i.itemFk = ieo.itemFk + WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ieo.warehouseOutFk = vWarehouseFk + GROUP BY ieo.itemFk, ieo.shipped + UNION ALL + SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) + FROM itemTicketOut ito + JOIN tmp.tItems i ON i.itemFk = ito.itemFk + WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ito.warehouseFk = vWarehouseFk + GROUP BY ito.itemFk, ito.shipped + ) t2 + JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t + GROUP BY t.itemFk, dated + ) t3; + + -- Se restan las entradas de hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed = util.VN_CURDATE() + AND iei.warehouseInFk = vWarehouseFk + AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock - sub.todayEntry + WHERE sbd.dated = util.VN_CURDATE(); + + -- Se añaden las lineas de venta servidas + UPDATE tmp.tStockByDay sbd + JOIN (SELECT s.itemFK, SUM(quantity) amount + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWarehouseFk + AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() + AND s.isPicked + GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + -- Se añaden los items ubicados hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT ish.itemFK, SUM(ish.visible) amount + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector s ON s.id = p.sectorFk + WHERE s.warehouseFk = vWarehouseFk + AND NOT s.isReserve + AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() + GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + SELECT ts.itemFk, + i.longName, + IF(ts.stock<=0, ts.dated, NULL) dated, + ts.stock, + sub4.visible, + sub4.shelvingFk + FROM( + SELECT IFNULL(sub2.minDated, sub.minDated) dated, + IFNULL(sub2.itemFk, sub.itemFk) itemFk + FROM(SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + GROUP BY itemFk)sub + LEFT JOIN ( + SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + WHERE sbd.stock <= 0 + GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk + WHERE sub2.itemFk IS NOT NULL + OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 + LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated + JOIN (SELECT ish.itemFk, + ish.visible, + p.sectorFk, + ish.shelvingFk + FROM itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = parkingFk + LEFT JOIN vn.sector s ON s.id = p.sectorFk + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + ) sub4 ON sub4.itemFk = ts.itemFk + LEFT JOIN sector s ON s.id = sub4.sectorFk + LEFT JOIN item i ON i.id = ts.itemFk + WHERE NOT s.isReserve; + + DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62333,50 +62333,50 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getAtp`(vDated DATE) -BEGIN -/** - * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y - * almacén. - * - * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 - * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) - * @return tmp.itemAtp(itemFk, warehouseFk, quantity) - */ - CREATE OR REPLACE TEMPORARY TABLE tItemOrdered - (UNIQUE(itemFk, warehouseFk, dated)) - ENGINE = MEMORY - SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity - FROM ( - SELECT itemFk, warehouseFk, dated, quantity - FROM tmp.itemCalc - UNION ALL - SELECT itemFk, warehouseFk, vDated, 0 - FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 - ) t1 - GROUP BY itemFk, warehouseFk, dated - ORDER BY itemFk, warehouseFk, dated; - - SET @lastItemFk := 0; - SET @lastWareHouseFk := 0; - SET @lastQuantity := 0; - - CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp - (INDEX (itemFk, wareHouseFk)) - SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity - FROM ( - SELECT - itemFk, - IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, - @lastQuantity := quantity, - @lastQuantity := @lastQuantity + quantity) quantityAccumulated, - wareHouseFk, - @lastItemFk := itemFk, - @lastWareHouseFk := wareHouseFk - FROM tItemOrdered - )sub - GROUP BY itemFk, wareHouseFk; - - DROP TEMPORARY TABLE tItemOrdered; +BEGIN +/** + * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y + * almacén. + * + * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 + * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) + * @return tmp.itemAtp(itemFk, warehouseFk, quantity) + */ + CREATE OR REPLACE TEMPORARY TABLE tItemOrdered + (UNIQUE(itemFk, warehouseFk, dated)) + ENGINE = MEMORY + SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity + FROM ( + SELECT itemFk, warehouseFk, dated, quantity + FROM tmp.itemCalc + UNION ALL + SELECT itemFk, warehouseFk, vDated, 0 + FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 + ) t1 + GROUP BY itemFk, warehouseFk, dated + ORDER BY itemFk, warehouseFk, dated; + + SET @lastItemFk := 0; + SET @lastWareHouseFk := 0; + SET @lastQuantity := 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp + (INDEX (itemFk, wareHouseFk)) + SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity + FROM ( + SELECT + itemFk, + IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, + @lastQuantity := quantity, + @lastQuantity := @lastQuantity + quantity) quantityAccumulated, + wareHouseFk, + @lastItemFk := itemFk, + @lastWareHouseFk := wareHouseFk + FROM tItemOrdered + )sub + GROUP BY itemFk, wareHouseFk; + + DROP TEMPORARY TABLE tItemOrdered; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64541,197 +64541,197 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( - vDate DATE, - vWarehouseFk TINYINT, - vMaxDays TINYINT +CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( + vDate DATE, + vWarehouseFk TINYINT, + vMaxDays TINYINT ) -proc: BEGIN - DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; - DECLARE vDateFrom DATE DEFAULT vDate; - DECLARE vDateTo DATETIME; - DECLARE vDateToTomorrow DATETIME; - DECLARE vDefaultDayRange INT; - - IF vDate < util.VN_CURDATE() THEN - LEAVE proc; - END IF; - - IF vDate = util.VN_CURDATE() THEN - SELECT inventoried INTO vDateFrom - FROM config; - END IF; - - SELECT defaultDayRange INTO vDefaultDayRange - FROM comparativeConfig; - - SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; - SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; - - ALTER TABLE tmp.itemInventory - ADD `avalaible` INT NOT NULL, - ADD `sd` INT NOT NULL, - ADD `rest` INT NOT NULL, - ADD `expected` INT NOT NULL, - ADD `inventory` INT NOT NULL, - ADD `visible` INT NOT NULL, - ADD `life` TINYINT NOT NULL DEFAULT '0'; - - -- Calculo del inventario - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.inventory = sub.Subtotal, - ai.visible = sub.Subtotal, - ai.avalaible = sub.Subtotal, - ai.sd = sub.Subtotal; - - -- Cálculo del visible - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.visible = ai.visible + sub.Subtotal; - - -- Calculo del disponible - CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT sub.itemFk, - vWarehouseFk warehouseFk, - sub.dated, - SUM(sub.quantity) quantity - FROM ( - SELECT s.itemFk, - DATE(t.shipped) dated, - - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, t.landed, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, t.shipped, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub - GROUP BY sub.itemFk, sub.dated; - - CALL item_getAtp(vDate); - CALL travel_upcomingArrivals(vWarehouseFk, vDate); - - UPDATE tmp.itemInventory ai - JOIN ( - SELECT it.itemFk, - SUM(it.quantity) quantity, - im.quantity minQuantity - FROM tmp.itemCalc it - JOIN tmp.itemAtp im ON im.itemFk = it.itemFk - JOIN item i ON i.id = it.itemFk - LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk - WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, - t.landing, - vDateToTomorrow) - GROUP BY it.itemFk - ) sub ON sub.itemFk = ai.id - SET ai.avalaible = IF(sub.minQuantity > 0, - ai.avalaible, - ai.avalaible + sub.minQuantity), - ai.sd = ai.inventory + sub.quantity; - - DROP TEMPORARY TABLE - tmp.itemTravel, - tmp.itemCalc, - tmp.itemAtp; +proc: BEGIN + DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; + DECLARE vDateFrom DATE DEFAULT vDate; + DECLARE vDateTo DATETIME; + DECLARE vDateToTomorrow DATETIME; + DECLARE vDefaultDayRange INT; + + IF vDate < util.VN_CURDATE() THEN + LEAVE proc; + END IF; + + IF vDate = util.VN_CURDATE() THEN + SELECT inventoried INTO vDateFrom + FROM config; + END IF; + + SELECT defaultDayRange INTO vDefaultDayRange + FROM comparativeConfig; + + SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; + SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; + + ALTER TABLE tmp.itemInventory + ADD `avalaible` INT NOT NULL, + ADD `sd` INT NOT NULL, + ADD `rest` INT NOT NULL, + ADD `expected` INT NOT NULL, + ADD `inventory` INT NOT NULL, + ADD `visible` INT NOT NULL, + ADD `life` TINYINT NOT NULL DEFAULT '0'; + + -- Calculo del inventario + UPDATE tmp.itemInventory ai + JOIN ( + SELECT itemFk Id_Article, SUM(quantity) Subtotal + FROM ( + SELECT s.itemFk, - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub2 + GROUP BY itemFk + ) sub ON ai.id = sub.Id_Article + SET ai.inventory = sub.Subtotal, + ai.visible = sub.Subtotal, + ai.avalaible = sub.Subtotal, + ai.sd = sub.Subtotal; + + -- Cálculo del visible + UPDATE tmp.itemInventory ai + JOIN ( + SELECT itemFk Id_Article, SUM(quantity) Subtotal + FROM ( + SELECT s.itemFk, s.quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped >= vDate + AND t.shipped < vDateTomorrow + AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + ) sub2 + GROUP BY itemFk + ) sub ON ai.id = sub.Id_Article + SET ai.visible = ai.visible + sub.Subtotal; + + -- Calculo del disponible + CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT sub.itemFk, + vWarehouseFk warehouseFk, + sub.dated, + SUM(sub.quantity) quantity + FROM ( + SELECT s.itemFk, + DATE(t.shipped) dated, + - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, t.landed, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, t.shipped, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub + GROUP BY sub.itemFk, sub.dated; + + CALL item_getAtp(vDate); + CALL travel_upcomingArrivals(vWarehouseFk, vDate); + + UPDATE tmp.itemInventory ai + JOIN ( + SELECT it.itemFk, + SUM(it.quantity) quantity, + im.quantity minQuantity + FROM tmp.itemCalc it + JOIN tmp.itemAtp im ON im.itemFk = it.itemFk + JOIN item i ON i.id = it.itemFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk + WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, + t.landing, + vDateToTomorrow) + GROUP BY it.itemFk + ) sub ON sub.itemFk = ai.id + SET ai.avalaible = IF(sub.minQuantity > 0, + ai.avalaible, + ai.avalaible + sub.minQuantity), + ai.sd = ai.inventory + sub.quantity; + + DROP TEMPORARY TABLE + tmp.itemTravel, + tmp.itemCalc, + tmp.itemAtp; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67555,43 +67555,43 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_merge`(vTicketFk INT) -BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; - - START TRANSACTION; - - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET s.quantity = newQuantity - WHERE s.ticketFk = vTicketFk; - - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND stp.id IS NULL - AND it.isMergeable; - - COMMIT; - - DROP TEMPORARY TABLE tSalesToPreserve; +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND it.isMergeable + GROUP BY s.itemFk, s.price, s.discount; + + START TRANSACTION; + + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET s.quantity = newQuantity + WHERE s.ticketFk = vTicketFk; + + DELETE s.* + FROM sale s + LEFT JOIN tSalesToPreserve stp ON stp.id = s.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND stp.id IS NULL + AND it.isMergeable; + + COMMIT; + + DROP TEMPORARY TABLE tSalesToPreserve; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69404,30 +69404,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN -/** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de #vn.sector - */ - DECLARE hasEmptyCollections BOOL; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk - AND sc.created >= util.VN_CURDATE(); - - IF NOT hasEmptyCollections THEN - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; +BEGIN +/** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de #vn.sector + */ + DECLARE hasEmptyCollections BOOL; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk + AND sc.created >= util.VN_CURDATE(); + + IF NOT hasEmptyCollections THEN + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73367,59 +73367,59 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT) -BEGIN -/** - * Splita las lineas de ticket que no estan ubicadas - * - * @param vTicketFk Id ticket - */ - DECLARE vNewTicketFk INT; - DECLARE vTotalLines INT; - DECLARE vLinesToSplit INT; - - DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; - - SELECT COUNT(*) INTO vTotalLines - FROM sale - WHERE ticketFk = vTicketFk; - - CREATE TEMPORARY TABLE tmp.SalesToSplit - SELECT s.id saleFk - FROM ticket t - JOIN sale s ON t.id = s.ticketFk - LEFT JOIN ( - SELECT ish.itemFk itemFk, - SUM(ish.visible) visible, - s.warehouseFk warehouseFk - FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector s ON s.id = p.sectorFk - GROUP BY ish.itemFk, - s.warehouseFk - ) issw ON issw.itemFk = s.itemFk - AND issw.warehouseFk = t.warehouseFk - WHERE s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND NOT s.isPicked - AND NOT s.reserved - AND t.id = vTicketFk; - - SELECT COUNT(*) INTO vLinesToSplit - FROM tmp.SalesToSplit; - - IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN - SET vNewTicketFk = vTicketFk; - ELSE - CALL ticket_Clone(vTicketFk, vNewTicketFk); - UPDATE sale s - JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id - SET s.ticketFk = vNewTicketFk; - END IF; - - CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); - - DROP TEMPORARY TABLE tmp.SalesToSplit; +BEGIN +/** + * Splita las lineas de ticket que no estan ubicadas + * + * @param vTicketFk Id ticket + */ + DECLARE vNewTicketFk INT; + DECLARE vTotalLines INT; + DECLARE vLinesToSplit INT; + + DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; + + SELECT COUNT(*) INTO vTotalLines + FROM sale + WHERE ticketFk = vTicketFk; + + CREATE TEMPORARY TABLE tmp.SalesToSplit + SELECT s.id saleFk + FROM ticket t + JOIN sale s ON t.id = s.ticketFk + LEFT JOIN ( + SELECT ish.itemFk itemFk, + SUM(ish.visible) visible, + s.warehouseFk warehouseFk + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector s ON s.id = p.sectorFk + GROUP BY ish.itemFk, + s.warehouseFk + ) issw ON issw.itemFk = s.itemFk + AND issw.warehouseFk = t.warehouseFk + WHERE s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND NOT s.isPicked + AND NOT s.reserved + AND t.id = vTicketFk; + + SELECT COUNT(*) INTO vLinesToSplit + FROM tmp.SalesToSplit; + + IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN + SET vNewTicketFk = vTicketFk; + ELSE + CALL ticket_Clone(vTicketFk, vNewTicketFk); + UPDATE sale s + JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id + SET s.ticketFk = vNewTicketFk; + END IF; + + CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); + + DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73437,84 +73437,84 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT) -BEGIN -/** -* Crea u actualiza la información del CMR asociado con -* un ticket específico en caso de que sea necesario. -* -* @param vSelf El id del ticket -*/ - DECLARE vCmrFk INT; - SELECT cmrFk INTO vCmrFk - FROM ticket - WHERE id = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tTicket - SELECT wo.firstName, - v.numberPlate, - com.id companyFk, - a.id addressFk, - c2.defaultAddressFk, - IFNULL(sat.supplierFk, su.id) supplierFk, - t.landed - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN company com ON com.id = t.companyFk - JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk - JOIN supplier su ON su.id = sa.supplierFk - LEFT JOIN route r ON r.id = t.routeFk - LEFT JOIN worker wo ON wo.id = r.workerFk - LEFT JOIN vehicle v ON v.id = r.vehicleFk - LEFT JOIN agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN agency ag ON ag.id = am.agencyFk - LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id - AND wo.isFreelance - WHERE al.code IN ('PACKED', 'DELIVERED') - AND co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND t.id = vSelf - GROUP BY t.id; - - IF vCmrFk THEN - UPDATE cmr c - JOIN tTicket t - SET c.senderInstruccions = t.firstName, - c.truckPlate = t.numberPlate, - c.companyFk = t.companyFk, - c.addressToFk = t.addressFk, - c.addressFromFk = t.defaultAddressFk, - c.supplierFk = t.supplierFk, - c.ead = t.landed - WHERE id = vCmrFk; - ELSE - INSERT INTO cmr ( - senderInstruccions, - truckPlate, - companyFk, - addressToFk, - addressFromFk, - supplierFk, - ead - ) - SELECT * FROM tTicket; - - IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN - UPDATE ticket - SET cmrFk = LAST_INSERT_ID() - WHERE id = vSelf; - END IF; - END IF; - - DROP TEMPORARY TABLE tTicket; +BEGIN +/** +* Crea u actualiza la información del CMR asociado con +* un ticket específico en caso de que sea necesario. +* +* @param vSelf El id del ticket +*/ + DECLARE vCmrFk INT; + SELECT cmrFk INTO vCmrFk + FROM ticket + WHERE id = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tTicket + SELECT wo.firstName, + v.numberPlate, + com.id companyFk, + a.id addressFk, + c2.defaultAddressFk, + IFNULL(sat.supplierFk, su.id) supplierFk, + t.landed + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN `address` a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN company com ON com.id = t.companyFk + JOIN client c2 ON c2.id = com.clientFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplier su ON su.id = sa.supplierFk + LEFT JOIN route r ON r.id = t.routeFk + LEFT JOIN worker wo ON wo.id = r.workerFk + LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN agency ag ON ag.id = am.agencyFk + LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id + AND wo.isFreelance + WHERE al.code IN ('PACKED', 'DELIVERED') + AND co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND t.id = vSelf + GROUP BY t.id; + + IF vCmrFk THEN + UPDATE cmr c + JOIN tTicket t + SET c.senderInstruccions = t.firstName, + c.truckPlate = t.numberPlate, + c.companyFk = t.companyFk, + c.addressToFk = t.addressFk, + c.addressFromFk = t.defaultAddressFk, + c.supplierFk = t.supplierFk, + c.ead = t.landed + WHERE id = vCmrFk; + ELSE + INSERT INTO cmr ( + senderInstruccions, + truckPlate, + companyFk, + addressToFk, + addressFromFk, + supplierFk, + ead + ) + SELECT * FROM tTicket; + + IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN + UPDATE ticket + SET cmrFk = LAST_INSERT_ID() + WHERE id = vSelf; + END IF; + END IF; + + DROP TEMPORARY TABLE tTicket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80930,126 +80930,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255), - vHasInsert BOOL +CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255), + vHasInsert BOOL ) -BEGIN -/** - * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. - * @param vSelf Id de la zona - * @param vParentFk Id del geo a calcular - * @param vSearch Cadena a buscar - * @param vHasInsert Indica si inserta en tmp.zoneNodes - * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - */ - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; - - CREATE OR REPLACE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id - FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk - FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - CREATE OR REPLACE TEMPORARY TABLE tChilds - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM tNodes; - - CREATE OR REPLACE TEMPORARY TABLE tParents - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF NOT ROW_COUNT() THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE tChilds, tParents; - END IF; - - IF NOT vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id - FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tZones - SELECT g.id, - g.name, - g.parentFk, - g.sons, - NOT g.sons OR `type` = 'country' isChecked, - i.isIncluded selected, - g.`depth`, - vSelf - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i ON i.geoFk = g.id - AND i.zoneFk = vSelf - ORDER BY g.`depth`, selected DESC, g.name; - - IF vHasInsert THEN - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT id, - name, - parentFk, - sons, - isChecked, - vSelf - FROM tZones - WHERE selected - OR (selected IS NULL AND vParentFk IS NOT NULL); - ELSE - SELECT id, - name, - parentFk, - sons, - selected - FROM tZones - ORDER BY `depth`, selected DESC, name; - END IF; - - DROP TEMPORARY TABLE tNodes, tZones; +BEGIN +/** + * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. + * @param vSelf Id de la zona + * @param vParentFk Id del geo a calcular + * @param vSearch Cadena a buscar + * @param vHasInsert Indica si inserta en tmp.zoneNodes + * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + */ + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; + + CREATE OR REPLACE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id + FROM zoneGeo + LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id + FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk + FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + CREATE OR REPLACE TEMPORARY TABLE tChilds + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM tNodes; + + CREATE OR REPLACE TEMPORARY TABLE tParents + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF NOT ROW_COUNT() THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE tChilds, tParents; + END IF; + + IF NOT vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id + FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tZones + SELECT g.id, + g.name, + g.parentFk, + g.sons, + NOT g.sons OR `type` = 'country' isChecked, + i.isIncluded selected, + g.`depth`, + vSelf + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i ON i.geoFk = g.id + AND i.zoneFk = vSelf + ORDER BY g.`depth`, selected DESC, g.name; + + IF vHasInsert THEN + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT id, + name, + parentFk, + sons, + isChecked, + vSelf + FROM tZones + WHERE selected + OR (selected IS NULL AND vParentFk IS NOT NULL); + ELSE + SELECT id, + name, + parentFk, + sons, + selected + FROM tZones + ORDER BY `depth`, selected DESC, name; + END IF; + + DROP TEMPORARY TABLE tNodes, tZones; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81232,48 +81232,48 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT) -BEGIN -/** - * Devuelve los códigos postales incluidos en una zona - */ - DECLARE vGeoFk INT DEFAULT NULL; - - CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( - geoFk INT, - name VARCHAR(100), - parentFk INT, - sons INT, - isChecked BOOL DEFAULT 0, - zoneFk INT, - PRIMARY KEY zoneNodesPk (zoneFk, geoFk), - INDEX(geoFk)) - ENGINE = MEMORY; - - CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); - - UPDATE tmp.zoneNodes - SET isChecked = 0 - WHERE parentFk IS NULL; - - myLoop: LOOP - SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk - FROM tmp.zoneNodes - WHERE NOT isChecked - LIMIT 1; - - CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); - UPDATE tmp.zoneNodes - SET isChecked = TRUE - WHERE geoFk = vGeoFk; - - IF vGeoFk IS NULL THEN - LEAVE myLoop; - END IF; - END LOOP; - - DELETE FROM tmp.zoneNodes - WHERE sons > 0; +BEGIN +/** + * Devuelve los códigos postales incluidos en una zona + */ + DECLARE vGeoFk INT DEFAULT NULL; + + CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( + geoFk INT, + name VARCHAR(100), + parentFk INT, + sons INT, + isChecked BOOL DEFAULT 0, + zoneFk INT, + PRIMARY KEY zoneNodesPk (zoneFk, geoFk), + INDEX(geoFk)) + ENGINE = MEMORY; + + CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); + + UPDATE tmp.zoneNodes + SET isChecked = 0 + WHERE parentFk IS NULL; + + myLoop: LOOP + SET vGeoFk = NULL; + SELECT geoFk INTO vGeoFk + FROM tmp.zoneNodes + WHERE NOT isChecked + LIMIT 1; + + CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); + UPDATE tmp.zoneNodes + SET isChecked = TRUE + WHERE geoFk = vGeoFk; + + IF vGeoFk IS NULL THEN + LEAVE myLoop; + END IF; + END LOOP; + + DELETE FROM tmp.zoneNodes + WHERE sons > 0; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; From 108a62f73870e319ce1aab5132a317101fe4f817 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 09:32:56 +0200 Subject: [PATCH 19/42] refs #7486 Fix tests --- db/routines/vn/procedures/collection_getAssigned.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/collection_getAssigned.sql b/db/routines/vn/procedures/collection_getAssigned.sql index bfaa3096b..947b53229 100644 --- a/db/routines/vn/procedures/collection_getAssigned.sql +++ b/db/routines/vn/procedures/collection_getAssigned.sql @@ -34,10 +34,10 @@ BEGIN pc.collection_assign_lockname INTO vHasTooMuchCollections, vLockName - FROM tCollection tc + FROM tmp.collection c JOIN productionConfig pc; - DROP TEMPORARY TABLE tCollection; + DROP TEMPORARY TABLE tmp.collection; IF vHasTooMuchCollections THEN CALL util.throw('There are pending collections'); From fcec3bc0ae24f5972281e3ce417a650671407b57 Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 4 Jul 2024 09:54:09 +0200 Subject: [PATCH 20/42] refs #5525 fix sql accountDetail --- print/templates/reports/sepa-core/sepa-core.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/print/templates/reports/sepa-core/sepa-core.js b/print/templates/reports/sepa-core/sepa-core.js index 96c512a9d..f32fd92e7 100755 --- a/print/templates/reports/sepa-core/sepa-core.js +++ b/print/templates/reports/sepa-core/sepa-core.js @@ -27,7 +27,8 @@ module.exports = { FROM supplierAccount sa JOIN company co ON co.supplierAccountFk = sa.id JOIN supplier s ON sa.supplierFk = s.id - WHERE co.id = ?`) [this.companyId]; + WHERE co.id = ? + AND ad.accountDetailTypeFk = 3`) [this.companyId]; } } From 776fd0564869de1019dd70df6972585fc894ee66 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 4 Jul 2024 12:45:52 +0200 Subject: [PATCH 21/42] fix: send rocket after commit cau 199307 --- modules/ticket/back/methods/sale/deleteSales.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/ticket/back/methods/sale/deleteSales.js b/modules/ticket/back/methods/sale/deleteSales.js index 0207815a9..0290b2b9d 100644 --- a/modules/ticket/back/methods/sale/deleteSales.js +++ b/modules/ticket/back/methods/sale/deleteSales.js @@ -66,6 +66,10 @@ module.exports = Self => { promises.push(deletedSale); } + const deletedSales = await Promise.all(promises); + + if (tx) await tx.commit(); + const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { const url = await Self.app.models.Url.getUrl(); @@ -75,13 +79,9 @@ module.exports = Self => { ticketUrl: `${url}ticket/${ticketId}/sale`, deletions: deletions }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); } - const deletedSales = await Promise.all(promises); - - if (tx) await tx.commit(); - return deletedSales; } catch (e) { if (tx) await tx.rollback(); From cf621071d07c849b072173ce1baf718eaa0c1c0c Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 4 Jul 2024 16:50:54 +0200 Subject: [PATCH 22/42] refs #5525 fixear sql, fixtures, js --- db/dump/fixtures.before.sql | 15 +++++++++++++++ print/templates/reports/sepa-core/sepa-core.html | 3 +-- print/templates/reports/sepa-core/sepa-core.js | 15 +++++++++------ .../templates/reports/sepa-core/sql/supplier.sql | 14 ++++++++------ 4 files changed, 33 insertions(+), 14 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index b6275d03c..05c1bbaa7 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3884,3 +3884,18 @@ INSERT INTO `vn`.`calendarHolidays` (calendarHolidaysTypeFk, dated, calendarHoli (1, '2001-05-17', 1, 5), (1, '2001-05-18', 1, 5); +INSERT INTO vn.accountDetail +(id, value, accountDetailTypeFk, supplierAccountFk) +VALUES + (21, 'ES12345B12345678', 3, 241), + (35, 'ES12346B12345679', 3, 241); + +INSERT INTO vn.accountDetailType +(id, description) +VALUES + (1, 'IBAN'), + (2, 'SWIFT'), + (3, 'Referencia Remesas'), + (4, 'Referencia Transferencias'), + (5, 'Referencia Nominas'), + (6, 'ABA'); diff --git a/print/templates/reports/sepa-core/sepa-core.html b/print/templates/reports/sepa-core/sepa-core.html index 363ebdfe5..e5d14d06c 100644 --- a/print/templates/reports/sepa-core/sepa-core.html +++ b/print/templates/reports/sepa-core/sepa-core.html @@ -27,8 +27,7 @@ {{$t('supplier.identifier')}} -
{{supplier.iban}}
-
{{supplier.nif}}
+
{{supplier.accountDetailValue.join(', ')}}
diff --git a/print/templates/reports/sepa-core/sepa-core.js b/print/templates/reports/sepa-core/sepa-core.js index f32fd92e7..6b941556e 100755 --- a/print/templates/reports/sepa-core/sepa-core.js +++ b/print/templates/reports/sepa-core/sepa-core.js @@ -7,7 +7,11 @@ module.exports = { async serverPrefetch() { this.client = await this.findOneFromDef('client', [this.companyId, this.companyId, this.id]); this.checkMainEntity(this.client); - this.supplier = await this.findOneFromDef('supplier', [this.companyId, this.companyId, this.id]); + const suppliers = await this.rawSqlFromDef('supplier', [this.companyId, this.companyId, this.id]); + this.supplier = { + ...suppliers[0], + accountDetailValue: suppliers.map(val => val?.accountDetailValue) + }; }, props: { id: { @@ -23,12 +27,11 @@ module.exports = { methods: { getSupplierCif() { return db.findOne(` - SELECT sa.iban, s.nif + SELECT DISTINCT ad.value FROM supplierAccount sa - JOIN company co ON co.supplierAccountFk = sa.id - JOIN supplier s ON sa.supplierFk = s.id - WHERE co.id = ? - AND ad.accountDetailTypeFk = 3`) [this.companyId]; + JOIN accountDetail ad ON ad.supplierAccountFk = sa.id + JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk AND adt.id = 3 + WHERE sa.supplierFk = ?`) [this.companyId]; } } diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql index 156fc71c0..a49896244 100644 --- a/print/templates/reports/sepa-core/sql/supplier.sql +++ b/print/templates/reports/sepa-core/sql/supplier.sql @@ -1,15 +1,16 @@ SELECT - m.code mandateCode, + m.code AS mandateCode, s.name, s.street, - sc.name country, + sc.name AS country, s.postCode, s.city, - sp.name province, + sp.name AS province, s.nif, sa.iban, sa.supplierFk, - be.name bankName + be.name AS bankName, + ad.value AS accountDetailValue FROM client c LEFT JOIN mandate m ON m.clientFk = c.id AND m.companyFk = ? AND m.finished IS NULL @@ -19,9 +20,10 @@ FROM LEFT JOIN province p ON p.id = c.provinceFk LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id LEFT JOIN bankEntity be ON sa.bankEntityFk = be.id + LEFT JOIN accountDetail ad ON ad.supplierAccountFk = sa.id + LEFT JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk AND adt.id = 3 WHERE (m.companyFk = ? OR m.companyFk IS NULL) AND (c.id = ? OR (c.id IS NULL AND c.countryFk = sa.countryFk)) ORDER BY - m.created DESC -LIMIT 1; + m.created DESC; From 64f5ad0e1960155c66c334a3b893a4a2d55c40fe Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 4 Jul 2024 16:54:57 +0200 Subject: [PATCH 23/42] refs #5525 remove AS --- print/templates/reports/sepa-core/sql/supplier.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql index a49896244..a32d311de 100644 --- a/print/templates/reports/sepa-core/sql/supplier.sql +++ b/print/templates/reports/sepa-core/sql/supplier.sql @@ -1,16 +1,16 @@ SELECT - m.code AS mandateCode, + m.code mandateCode, s.name, s.street, - sc.name AS country, + sc.name country, s.postCode, s.city, - sp.name AS province, + sp.name province, s.nif, sa.iban, sa.supplierFk, - be.name AS bankName, - ad.value AS accountDetailValue + be.name bankName, + ad.value accountDetailValue FROM client c LEFT JOIN mandate m ON m.clientFk = c.id AND m.companyFk = ? AND m.finished IS NULL From 859f610f43a1760631bd24bc16fe013b3ea8a526 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 5 Jul 2024 08:43:45 +0200 Subject: [PATCH 24/42] hotFix itemNewer refs #6964 --- .../methods/item-shelving/getListItemNewer.js | 2 +- .../specs/getListItemNewer.spec.js | 25 +++++-------------- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/modules/item/back/methods/item-shelving/getListItemNewer.js b/modules/item/back/methods/item-shelving/getListItemNewer.js index 1702bb05b..dafefe712 100644 --- a/modules/item/back/methods/item-shelving/getListItemNewer.js +++ b/modules/item/back/methods/item-shelving/getListItemNewer.js @@ -63,7 +63,7 @@ module.exports = Self => { FROM tItemShelving ti JOIN tItemInSector tis ON tis.itemFk = ti.itemFk JOIN vn.productionConfig pc - WHERE ti.created > tis.created + INTERVAL pc.itemOlderReviewHours HOUR;`, + WHERE ti.created + INTERVAL pc.itemOlderReviewHours HOUR < tis.created ;`, [shelvingFk, shelvingFk], myOptions); return result; }; diff --git a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js index 15c480992..9287a179d 100644 --- a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js @@ -2,30 +2,17 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving getListItemNewer()', () => { - it('should return true because there is an older item', async() => { - const shelving = 'NCC'; - const parking = 'A-47-1'; + fit('should return true because there is an older item', async() => { + const shelving = 'NBB'; + const parking = '700-01'; - const sectorCamHighCode = 'CAMARA SECTOR D'; - const sectorCamCode = 'NAVE ALGEMESI'; - - const sectorCamCodeHighId = 1; - const sectorCamCodeId = 9991; + const sectorCamHighCode = 'FIRST'; + const sectorCamCode = 'NS'; const tx = await models.Sector.beginTransaction({}); const myOptions = {transaction: tx}; try { - const sectorHighCam = await models.Sector.findById(sectorCamCodeHighId, null, myOptions); - await sectorHighCam.updateAttributes({ - code: sectorCamHighCode - }); - - const sectorCam = await models.Sector.findById(sectorCamCodeId, null, myOptions); - await sectorCam.updateAttributes({ - code: sectorCamCode - }); - const config = await models.ProductionConfig.findOne(); await config.updateAttributes({ @@ -35,7 +22,7 @@ describe('itemShelving getListItemNewer()', () => { const result = await models.ItemShelving.getListItemNewer(shelving, parking, myOptions); - expect(result.length).toEqual(2); + expect(result.length).toEqual(3); await tx.rollback(); } catch (e) { await tx.rollback(); From 159f2f5f1c4b73a48fc994c1a17d97a48038e1b6 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 5 Jul 2024 08:44:09 +0200 Subject: [PATCH 25/42] hotFix itemNewer refs #6964 --- .../back/methods/item-shelving/specs/getListItemNewer.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js index 9287a179d..962863095 100644 --- a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js @@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving getListItemNewer()', () => { - fit('should return true because there is an older item', async() => { + it('should return true because there is an older item', async() => { const shelving = 'NBB'; const parking = '700-01'; From 923efadf6a760bbeb207e096acf20861cc83bc50 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 5 Jul 2024 09:00:40 +0200 Subject: [PATCH 26/42] fix: refs #6371 restore table Series --- db/dump/.dump/structure.sql | 44 +++++++++---------- .../11134-silverRaphis/00-firstScript.sql | 42 ++++++++++++++++++ 2 files changed, 64 insertions(+), 22 deletions(-) create mode 100644 db/versions/11134-silverRaphis/00-firstScript.sql diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 6797c01a5..5755ce085 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -19,7 +19,7 @@ -- Current Database: `account` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 */ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `account`; @@ -2230,7 +2230,7 @@ DELIMITER ; -- Current Database: `bi` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bi`; @@ -4000,7 +4000,7 @@ DELIMITER ; -- Current Database: `bs` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bs`; @@ -6967,7 +6967,7 @@ DELIMITER ; -- Current Database: `cache` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `cache`; @@ -8087,7 +8087,7 @@ DELIMITER ; -- Current Database: `dipole` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `dipole`; @@ -8316,7 +8316,7 @@ DELIMITER ; -- Current Database: `edi` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `edi`; @@ -11054,7 +11054,7 @@ DELIMITER ; -- Current Database: `floranet` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `floranet`; @@ -11638,7 +11638,7 @@ DELIMITER ; -- Current Database: `hedera` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `hedera`; @@ -15833,7 +15833,7 @@ DELIMITER ; -- Current Database: `pbx` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `pbx`; @@ -16499,7 +16499,7 @@ DELIMITER ; -- Current Database: `psico` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `psico`; @@ -16834,7 +16834,7 @@ DELIMITER ; -- Current Database: `sage` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 */ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `sage`; @@ -19146,7 +19146,7 @@ DELIMITER ; -- Current Database: `salix` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `salix`; @@ -19440,7 +19440,7 @@ DELIMITER ; -- Current Database: `srt` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `srt`; @@ -22991,7 +22991,7 @@ DELIMITER ; -- Current Database: `stock` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 */ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `stock`; @@ -24069,7 +24069,7 @@ DELIMITER ; -- Current Database: `tmp` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `tmp`; @@ -24147,7 +24147,7 @@ DELIMITER ; -- Current Database: `util` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `util`; @@ -26252,7 +26252,7 @@ DELIMITER ; -- Current Database: `vn` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn`; @@ -63220,7 +63220,7 @@ BEGIN * @param vDate -> Date of the purchase operation. * @param vWarehouseFk -> Identifier of the warehouse (warehouseId). */ - ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT; + ALTER TABLE tmp.itemInventory ADD buy_id INT; CALL buyUltimate(vWarehouseFk, vDate); @@ -68883,7 +68883,7 @@ proc: BEGIN CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN + (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk)); END IF; @@ -77852,11 +77852,11 @@ BEGIN IF vWorkerFk THEN CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE tmp.`user` SELECT vWorkerFk userFk; ELSE CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk FROM worker w; END IF; @@ -81544,7 +81544,7 @@ DELIMITER ; -- Current Database: `vn2008` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn2008`; diff --git a/db/versions/11134-silverRaphis/00-firstScript.sql b/db/versions/11134-silverRaphis/00-firstScript.sql new file mode 100644 index 000000000..0836abe4e --- /dev/null +++ b/db/versions/11134-silverRaphis/00-firstScript.sql @@ -0,0 +1,42 @@ +USE `vn`; + +CREATE TABLE IF NOT EXISTS vn.`tillSerial` ( + `code` varchar(2) COLLATE utf8mb3_unicode_ci NOT NULL, + `description` varchar(30) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `account` varchar(10) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES(' S', 'Saldos final / inicial', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('A', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('B', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('C', 'Facturas Contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CC', 'Cuadre caja', '6780000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CD', 'Cuenta Director Comercial', '5510000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CH', 'Cheques', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CM', 'Cambio', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CR', 'Ingreso/Reintegro Caja Rural', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CT', 'Correos y telégrafos', '6290000005'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DC', 'Dietas conductores', '6290000010'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DH', 'Deudas Holland', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DT', 'Dietas', '6290000011'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('E', 'Entrada mercancia', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('EN', 'Enric Martinez', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GC', 'Cuenta con dto. Comercial', '5510000003'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GP', 'Gastos de personal', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GR', 'Gastos RRPP dpto comercial', '6290001002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GS', 'Gasoil', '6280000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GV', 'Gastos viaje', '6290001000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('JV', 'Juanvi', '6290000553'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MB', 'Movimiento bancario', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MP', 'Materias Primas', '6000000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('OG', 'Otros gastos', '6290000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('PM', 'Pequeño material', '6290000007'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('R', 'Factura proveedor', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RC', 'Ingreso/Reintegro Ruralcaja', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RN', 'Reparación nave', '6220000004'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('SS', 'Gastos Silla', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('T', 'Ticket', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TA', 'Factura rapida', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TC', 'Ticket contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TR', 'Traspaso', NULL); \ No newline at end of file From 27a4b747b5595a50087b34ae0fa866612bd09d0b Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 5 Jul 2024 09:05:39 +0200 Subject: [PATCH 27/42] fix: refs #6371 restore table Series --- .../11134-silverRaphis/00-firstScript.sql | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 db/versions/11134-silverRaphis/00-firstScript.sql diff --git a/db/versions/11134-silverRaphis/00-firstScript.sql b/db/versions/11134-silverRaphis/00-firstScript.sql new file mode 100644 index 000000000..0836abe4e --- /dev/null +++ b/db/versions/11134-silverRaphis/00-firstScript.sql @@ -0,0 +1,42 @@ +USE `vn`; + +CREATE TABLE IF NOT EXISTS vn.`tillSerial` ( + `code` varchar(2) COLLATE utf8mb3_unicode_ci NOT NULL, + `description` varchar(30) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `account` varchar(10) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES(' S', 'Saldos final / inicial', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('A', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('B', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('C', 'Facturas Contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CC', 'Cuadre caja', '6780000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CD', 'Cuenta Director Comercial', '5510000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CH', 'Cheques', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CM', 'Cambio', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CR', 'Ingreso/Reintegro Caja Rural', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CT', 'Correos y telégrafos', '6290000005'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DC', 'Dietas conductores', '6290000010'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DH', 'Deudas Holland', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DT', 'Dietas', '6290000011'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('E', 'Entrada mercancia', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('EN', 'Enric Martinez', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GC', 'Cuenta con dto. Comercial', '5510000003'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GP', 'Gastos de personal', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GR', 'Gastos RRPP dpto comercial', '6290001002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GS', 'Gasoil', '6280000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GV', 'Gastos viaje', '6290001000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('JV', 'Juanvi', '6290000553'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MB', 'Movimiento bancario', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MP', 'Materias Primas', '6000000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('OG', 'Otros gastos', '6290000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('PM', 'Pequeño material', '6290000007'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('R', 'Factura proveedor', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RC', 'Ingreso/Reintegro Ruralcaja', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RN', 'Reparación nave', '6220000004'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('SS', 'Gastos Silla', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('T', 'Ticket', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TA', 'Factura rapida', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TC', 'Ticket contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TR', 'Traspaso', NULL); \ No newline at end of file From 182273d3b387c35cd40d296eceee468381d4ca4a Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 09:59:15 +0200 Subject: [PATCH 28/42] refs #7450 Modified msg throw --- db/routines/vn/procedures/entry_isEditable.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql index a05a1fd92..c279fac65 100644 --- a/db/routines/vn/procedures/entry_isEditable.sql +++ b/db/routines/vn/procedures/entry_isEditable.sql @@ -18,7 +18,7 @@ BEGIN AND e.id = vSelf; IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN - CALL util.throw('Entry is not editable'); + CALL util.throw(CONCAT('Entry ', vSelf, ' is not editable')); END IF; END$$ DELIMITER ; From 3051e4ed251a7dc25a96efdee607769b79c4f2d7 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 5 Jul 2024 10:35:32 +0200 Subject: [PATCH 29/42] Merge branch '6371-restoreSeries' of https://gitea.verdnatura.es/verdnatura/salix into 6371-restoreSeries --- db/dump/.dump/structure.sql | 44 ++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 5755ce085..6797c01a5 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -19,7 +19,7 @@ -- Current Database: `account` -- -CREATE DATABASE /*!32312 */ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `account`; @@ -2230,7 +2230,7 @@ DELIMITER ; -- Current Database: `bi` -- -CREATE DATABASE /*!32312 */ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bi`; @@ -4000,7 +4000,7 @@ DELIMITER ; -- Current Database: `bs` -- -CREATE DATABASE /*!32312 */ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bs`; @@ -6967,7 +6967,7 @@ DELIMITER ; -- Current Database: `cache` -- -CREATE DATABASE /*!32312 */ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `cache`; @@ -8087,7 +8087,7 @@ DELIMITER ; -- Current Database: `dipole` -- -CREATE DATABASE /*!32312 */ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `dipole`; @@ -8316,7 +8316,7 @@ DELIMITER ; -- Current Database: `edi` -- -CREATE DATABASE /*!32312 */ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `edi`; @@ -11054,7 +11054,7 @@ DELIMITER ; -- Current Database: `floranet` -- -CREATE DATABASE /*!32312 */ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `floranet`; @@ -11638,7 +11638,7 @@ DELIMITER ; -- Current Database: `hedera` -- -CREATE DATABASE /*!32312 */ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `hedera`; @@ -15833,7 +15833,7 @@ DELIMITER ; -- Current Database: `pbx` -- -CREATE DATABASE /*!32312 */ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `pbx`; @@ -16499,7 +16499,7 @@ DELIMITER ; -- Current Database: `psico` -- -CREATE DATABASE /*!32312 */ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `psico`; @@ -16834,7 +16834,7 @@ DELIMITER ; -- Current Database: `sage` -- -CREATE DATABASE /*!32312 */ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `sage`; @@ -19146,7 +19146,7 @@ DELIMITER ; -- Current Database: `salix` -- -CREATE DATABASE /*!32312 */ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `salix`; @@ -19440,7 +19440,7 @@ DELIMITER ; -- Current Database: `srt` -- -CREATE DATABASE /*!32312 */ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `srt`; @@ -22991,7 +22991,7 @@ DELIMITER ; -- Current Database: `stock` -- -CREATE DATABASE /*!32312 */ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `stock`; @@ -24069,7 +24069,7 @@ DELIMITER ; -- Current Database: `tmp` -- -CREATE DATABASE /*!32312 */ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `tmp`; @@ -24147,7 +24147,7 @@ DELIMITER ; -- Current Database: `util` -- -CREATE DATABASE /*!32312 */ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `util`; @@ -26252,7 +26252,7 @@ DELIMITER ; -- Current Database: `vn` -- -CREATE DATABASE /*!32312 */ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn`; @@ -63220,7 +63220,7 @@ BEGIN * @param vDate -> Date of the purchase operation. * @param vWarehouseFk -> Identifier of the warehouse (warehouseId). */ - ALTER TABLE tmp.itemInventory ADD buy_id INT; + ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT; CALL buyUltimate(vWarehouseFk, vDate); @@ -68883,7 +68883,7 @@ proc: BEGIN CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN + IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk)); END IF; @@ -77852,11 +77852,11 @@ BEGIN IF vWorkerFk THEN CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); - CREATE TEMPORARY TABLE tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT vWorkerFk userFk; ELSE CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); - CREATE TEMPORARY TABLE tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT id userFk FROM worker w; END IF; @@ -81544,7 +81544,7 @@ DELIMITER ; -- Current Database: `vn2008` -- -CREATE DATABASE /*!32312 */ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn2008`; From f3f450463b628ac57cb811985e3659519bf0fe70 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 5 Jul 2024 10:47:26 +0200 Subject: [PATCH 30/42] warmFix getSales refs #6861 --- back/methods/collection/getSales.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index 8f5bfaeef..a9e5f2e60 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -60,15 +60,17 @@ module.exports = Self => { if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); for (let ticket of tickets) { - let observations = ticket.observaciones.split(' '); + if (ticket.observaciones) { + let observations = ticket.observaciones.split(' '); - for (let observation of observations) { - const salesPerson = ticket.salesPersonFk; - if (observation.startsWith('#') || observation.startsWith('@')) { - await models.Chat.send(ctx, - observation, - $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) - ); + for (let observation of observations) { + const salesPerson = ticket.salesPersonFk; + if (observation.startsWith('#') || observation.startsWith('@')) { + await models.Chat.send(ctx, + observation, + $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) + ); + } } } } From 8ac26c7281ca26fa9110389783c7128ee90d0967 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 12:50:31 +0200 Subject: [PATCH 31/42] refactor: refs #7640 Refactor multipleInventory --- .../vn/procedures/multipleInventory.sql | 85 ++++++++++--------- 1 file changed, 43 insertions(+), 42 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index ece57727d..704a93152 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -76,52 +76,52 @@ proc: BEGIN GROUP BY itemFk; -- Cálculo del visible - UPDATE tItemInventoryCalc iic - JOIN ( - SELECT itemFk, SUM(quantity) visible - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON sub.itemFk = iic.itemFk - SET iic.visible = iic.visible + sub.visible; + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) visible + FROM ( + SELECT s.itemFk, s.quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped >= vDate + AND t.shipped < vDateTomorrow + AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + ) sub2 + GROUP BY itemFk; UPDATE tmp.itemInventory ai JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id SET ai.inventory = iic.quantity, - ai.visible = iic.visible, + ai.visible = iic.quantity + ivc.visible, ai.avalaible = iic.quantity, ai.sd = iic.quantity; @@ -195,6 +195,7 @@ proc: BEGIN tmp.itemTravel, tmp.itemCalc, tItemInventoryCalc, + tItemVisibleCalc, tmp.itemAtp; END$$ DELIMITER ; From 1d59883d19f96020ec7d377cc965c975821b60e0 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:14:16 +0200 Subject: [PATCH 32/42] feat: refs #7644 Minor change --- print/templates/reports/buy-label/buy-label.html | 2 +- print/templates/reports/buy-label/sql/buys.sql | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/print/templates/reports/buy-label/buy-label.html b/print/templates/reports/buy-label/buy-label.html index 494cdcbc5..b14e54759 100644 --- a/print/templates/reports/buy-label/buy-label.html +++ b/print/templates/reports/buy-label/buy-label.html @@ -59,7 +59,7 @@
- {{buy.id}} + {{buy.itemFk}} diff --git a/print/templates/reports/buy-label/sql/buys.sql b/print/templates/reports/buy-label/sql/buys.sql index 50b34bd03..41fd3556b 100644 --- a/print/templates/reports/buy-label/sql/buys.sql +++ b/print/templates/reports/buy-label/sql/buys.sql @@ -8,6 +8,7 @@ SELECT ROW_NUMBER() OVER(ORDER BY b.id) labelNum, b.`grouping`, i.stems, b.id, + b.itemFk, p.name producer FROM buy b JOIN item i ON i.id = b.itemFk From 3ddf49da0afdbd00b7f4c8466668149b439cacc1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:21:07 +0200 Subject: [PATCH 33/42] feat: refs #7640 Fix --- db/routines/vn/procedures/multipleInventory.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 704a93152..8eb4dae71 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -119,9 +119,9 @@ proc: BEGIN UPDATE tmp.itemInventory ai JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id - JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id + LEFT JOIN tItemVisibleCalc ivc ON ivc.itemFk = iic.itemFk SET ai.inventory = iic.quantity, - ai.visible = iic.quantity + ivc.visible, + ai.visible = iic.visible + IFNULL(ivc.visible, 0), ai.avalaible = iic.quantity, ai.sd = iic.quantity; From 55f0e907711b4090fa7c97caf4f54817414d882f Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:36:38 +0200 Subject: [PATCH 34/42] feat: refs #7640 Minor change --- db/routines/vn/procedures/multipleInventory.sql | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 8eb4dae71..662aa2d63 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -75,6 +75,13 @@ proc: BEGIN ) sub GROUP BY itemFk; + UPDATE tmp.itemInventory ai + JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + SET ai.inventory = iic.quantity, + ai.visible = iic.visible, + ai.avalaible = iic.quantity, + ai.sd = iic.quantity; + -- Cálculo del visible CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc (PRIMARY KEY (itemFk)) @@ -118,12 +125,8 @@ proc: BEGIN GROUP BY itemFk; UPDATE tmp.itemInventory ai - JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id - LEFT JOIN tItemVisibleCalc ivc ON ivc.itemFk = iic.itemFk - SET ai.inventory = iic.quantity, - ai.visible = iic.visible + IFNULL(ivc.visible, 0), - ai.avalaible = iic.quantity, - ai.sd = iic.quantity; + JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id + SET ai.visible = ai.visible + ivc.visible; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc From 592738c7a0c3d39da8c75c6f7fc365023c5402f7 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:48:03 +0200 Subject: [PATCH 35/42] refs #7024 & ticket 198125 Hotfix --- db/routines/vn/triggers/entry_beforeUpdate.sql | 2 -- 1 file changed, 2 deletions(-) diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 31c6f9bd6..0a161853b 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -11,11 +11,9 @@ BEGIN IF NEW.isBooked = OLD.isBooked AND ( NOT (NEW.supplierFk <=> OLD.supplierFk) OR NOT (NEW.dated <=> OLD.dated) OR - NOT (NEW.invoiceNumber <=> OLD.invoiceNumber) OR NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.companyFk <=> OLD.companyFk) OR NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) OR - NOT (NEW.invoiceAmount <=> OLD.invoiceAmount) OR NOT (NEW.typeFk <=> OLD.typeFk) ) THEN From 3508cf3a9eea30366065b002e4135fce13590a17 Mon Sep 17 00:00:00 2001 From: ivanm Date: Fri, 5 Jul 2024 14:01:09 +0200 Subject: [PATCH 36/42] refs #7561 add fk en userFk --- db/versions/11137-salmonRoebelini/00-firstScript.sql | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 db/versions/11137-salmonRoebelini/00-firstScript.sql diff --git a/db/versions/11137-salmonRoebelini/00-firstScript.sql b/db/versions/11137-salmonRoebelini/00-firstScript.sql new file mode 100644 index 000000000..69d20ac6d --- /dev/null +++ b/db/versions/11137-salmonRoebelini/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.expeditionState + MODIFY COLUMN userFk INT(10) UNSIGNED, + ADD CONSTRAINT expeditionState_userFk FOREIGN KEY (userFk) + REFERENCES account.`user`(id); \ No newline at end of file From 5192bfd8ead52327c2b474465f231b8e596466c8 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 5 Jul 2024 14:58:34 +0200 Subject: [PATCH 37/42] fix(salix): refs #7648 #7648 entryFilter and getBuys by fi --- modules/entry/back/methods/entry/filter.js | 7 ++++--- modules/entry/back/methods/entry/getBuys.js | 7 ++++--- modules/entry/back/methods/entry/specs/filter.spec.js | 4 ++-- modules/entry/back/methods/entry/specs/getBuys.spec.js | 2 +- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 5989494a4..f21d9dbc4 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -146,10 +146,11 @@ module.exports = Self => { }); filter = mergeFilters(ctx.args.filter, {where}); const userId = ctx.req.accessToken.userId; - const isSupplier = await Self.app.models.Supplier.findById(userId, myOptions); - if (isSupplier) { + const client = await Self.app.models.Client.findById(userId, myOptions); + const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions); + if (supplier) { if (!filter.where) filter.where = {}; - filter.where[`e.supplierFk`] = ctx.req.accessToken.userId; + filter.where[`e.supplierFk`] = supplier.id; } const stmts = []; let stmt; diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index 444e6cb14..0cb71653e 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -36,9 +36,10 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const isSupplier = await Self.app.models.Supplier.findById(userId, myOptions); - if (isSupplier) { - const isEntryOwner = (await Self.findById(id)).supplierFk === userId; + const client = await Self.app.models.Client.findById(userId, myOptions); + const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions); + if (supplier) { + const isEntryOwner = (await Self.findById(id)).supplierFk === supplier.id; if (!isEntryOwner) throw new UserError('Access Denied'); } diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index 9d954cdc4..c8a5bd94f 100644 --- a/modules/entry/back/methods/entry/specs/filter.spec.js +++ b/modules/entry/back/methods/entry/specs/filter.spec.js @@ -56,7 +56,7 @@ describe('Entry filter()', () => { try { const ctx = { args: {}, - req: {accessToken: {userId: 2}} + req: {accessToken: {userId: 1102}} }; const result = await models.Entry.filter(ctx, options); @@ -79,7 +79,7 @@ describe('Entry filter()', () => { args: { supplierFk: 1 }, - req: {accessToken: {userId: 2}} + req: {accessToken: {userId: 1102}} }; const result = await models.Entry.filter(ctx, options); diff --git a/modules/entry/back/methods/entry/specs/getBuys.spec.js b/modules/entry/back/methods/entry/specs/getBuys.spec.js index cb7f7cb80..2d3531249 100644 --- a/modules/entry/back/methods/entry/specs/getBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/getBuys.spec.js @@ -40,7 +40,7 @@ describe('entry getBuys()', () => { args: { search: 1 }, - req: {accessToken: {userId: 2}} + req: {accessToken: {userId: 1102}} }; const result = await models.Entry.getBuys(ctx, entryId, options); From 3a2acfb7f8e5e012704c9e3496375521416d06c8 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 07:21:53 +0200 Subject: [PATCH 38/42] feat: refs #7640 Optimization --- db/routines/vn/procedures/multipleInventory.sql | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 662aa2d63..941ac6c3d 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -40,8 +40,7 @@ proc: BEGIN (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT itemFk, - SUM(quantity) quantity, - SUM(quantity) visible + SUM(quantity) quantity FROM ( SELECT s.itemFk, - s.quantity quantity FROM sale s @@ -78,7 +77,7 @@ proc: BEGIN UPDATE tmp.itemInventory ai JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id SET ai.inventory = iic.quantity, - ai.visible = iic.visible, + ai.visible = iic.quantity, ai.avalaible = iic.quantity, ai.sd = iic.quantity; From e9d2ff14764bfc5eddcc1e0121de93d183c71546 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 09:43:59 +0200 Subject: [PATCH 39/42] feat: refs #7582 claimDestination addColumn code --- db/versions/11138-aquaGalax/00-firstScript.sql | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 db/versions/11138-aquaGalax/00-firstScript.sql diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql new file mode 100644 index 000000000..44fdd468f --- /dev/null +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -0,0 +1,9 @@ +USE `vn`; +ALTER TABLE `vn`.`claimDestination` +ADD COLUMN `code` varchar(45) DEFAULT NULL; + +UPDATE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; +UPDATE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; +UPDATE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; +UPDATE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; +UPDATE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file From 3fa0823d931bc8a817772f0ed855172151e537c5 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 11:01:35 +0200 Subject: [PATCH 40/42] feat: refs #7582 quitar vn --- db/versions/11138-aquaGalax/00-firstScript.sql | 1 - 1 file changed, 1 deletion(-) diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql index 44fdd468f..1e759db61 100644 --- a/db/versions/11138-aquaGalax/00-firstScript.sql +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -1,4 +1,3 @@ -USE `vn`; ALTER TABLE `vn`.`claimDestination` ADD COLUMN `code` varchar(45) DEFAULT NULL; From a796787cb5eb3da34a893f25c79c7d52ff939aa0 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 11:04:35 +0200 Subject: [PATCH 41/42] feat: refs #7582 --- db/versions/11138-aquaGalax/00-firstScript.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql index 1e759db61..0c6547260 100644 --- a/db/versions/11138-aquaGalax/00-firstScript.sql +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -1,8 +1,8 @@ ALTER TABLE `vn`.`claimDestination` ADD COLUMN `code` varchar(45) DEFAULT NULL; -UPDATE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; -UPDATE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; -UPDATE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; -UPDATE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; -UPDATE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file +UPDATE IGNORE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; +UPDATE IGNORE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; +UPDATE IGNORE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; +UPDATE IGNORE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; +UPDATE IGNORE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file From 0722a97c6000bd9ebc36b9349589bd660ee5e31a Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 11:28:33 +0200 Subject: [PATCH 42/42] feat: refs #7582 --- db/versions/11138-aquaGalax/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql index 0c6547260..d492e6470 100644 --- a/db/versions/11138-aquaGalax/00-firstScript.sql +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -3,6 +3,6 @@ ADD COLUMN `code` varchar(45) DEFAULT NULL; UPDATE IGNORE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; UPDATE IGNORE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; -UPDATE IGNORE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; +UPDATE IGNORE vn.claimDestination SET code='Manufacturing' WHERE description = 'Confeccion'; UPDATE IGNORE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; UPDATE IGNORE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file