From d72f2419468132cb955d8d9a3fa4fe933edac22b Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 23 Mar 2020 08:24:57 +0100 Subject: [PATCH 01/25] first commit --- .DS_Store | Bin 0 -> 8196 bytes back/.DS_Store | Bin 0 -> 6148 bytes back/methods/.DS_Store | Bin 0 -> 6148 bytes back/methods/collection/collectionGet.js | 22 +++++ back/methods/collection/collectionNew.js | 120 +++++++++++++++++++++++ back/methods/collection/getSectors.js | 20 ++++ back/model-config.json | 3 + back/models/collection.js | 5 + back/models/collection.json | 12 +++ loopback/.DS_Store | Bin 0 -> 6148 bytes 10 files changed, 182 insertions(+) create mode 100644 .DS_Store create mode 100644 back/.DS_Store create mode 100644 back/methods/.DS_Store create mode 100644 back/methods/collection/collectionGet.js create mode 100644 back/methods/collection/collectionNew.js create mode 100644 back/methods/collection/getSectors.js create mode 100644 back/models/collection.js create mode 100644 back/models/collection.json create mode 100644 loopback/.DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..f0821349b2196b034eb2201ebee8f9ea8fe4d886 GIT binary patch literal 8196 zcmeHM(M}UV6ukq*ZVLz)6L@o9OniU_F(Ss8)B+C}F~%BwPy=1Mmddi*bXzLcn!flC z>L2(ieu2N>yC0zE&Mb9yy9J+&kr^^`XLrw;nLTr7rgtGCQEFGO6D<&th0Jz#5=Bbl z=bVSqSajzKtN@?rfLv-)ooeI{q0J4WfKk9GU=%P47zO?X1#o6_vPPWy>ZvJ>0!D#z zsQ~W}HZt2{Wc$j>tpkM&0bnz@Efea910=_eY%#KZWhE7Ds^~#PR1t+3LecTuW;kpy zvVCP0orI#3hYG7IpJM(DCihyPV>%=+ z-lzDGU}k`;@mLeM9|>Ik1UGtAW0eFa3(gURQh{o!ZXY$>X2_umvWxdG=&IrBHHGo< z5o@QjGm?$jisPhGI&KUz<0LSwiH^z0*$Y!O(Q%hz9np5P$Y($ls<>nXglg5MMu^r#+m@DDLppn5l|_HoP^)BG1|tU zpS1SjM+w$_jL65TVjmArxbYcbm13-Ecz_FZi_o23V| zMeDRl52;L>@i9u}^qwqe5#X;e!V_7)Q}IqGY()FYSEu3C!`AZhH!(JznYfU(th|+< z&c7`02c2@O(rSmLO7l5iJ*u?!ov8jK2)seP;ykUpot@ds>w({@)P1)p$@QuW$ctxn zzZ!H(LEEo}vYoPeU|BgUw==uY?cQEnU9?wLS9^h9_x=->4w8s|fzXV)9+aO^8xrQI-1NP`uQ3rhi)|{vQetPqBqwBM2hwGmg4;0K zrJd7w(uH*1944lMC3=9e2KJJiF20s-i#Gju&%CjV@0u%3C0ZE8u9_p2rt>_j?ajyiZ3XE3reom{YnkfMC}cPeE5mWv!9NU9w*h5N dF|vJSaR=$Ie+b}T73TbppS9-vm%ezOieD3RXrcfB literal 0 HcmV?d00001 diff --git a/back/.DS_Store b/back/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a15d86adb3a8380cd195bb108ab8ed68193beb99 GIT binary patch literal 6148 zcmeHK%}(1u5S~raViT!yB@R^T!BP*sa0n_PJz9bEgw(1=pbKp%n^;oh0u4JxEPf=D$Z&3@zgTl=%M>jePO9Y(7F4ggrFgf$z7zX-)i zXQXC4ghKU@5J3@+ii0qn$!5o6WPsk?0(^rQN*KT&?@xvpxegD~q$pdhD^aUAo;+Q! z?8TLn~(>*@#Bv~X!T{+C6Lgkz0%Ki|P1MFkH^1?I4sBPJOXL&qs zciJoN+S}G-#T|D#EwtaPPbRiyy?FiZ#r>{A86pH#mh~XxyRX z(9g3}X8RbKR!y@RnE_^i8JI%`%u;4G=kVV7mYD%&;C>mP^}$6Y^bA%S)zX0j{XSB> zK}do&oh1legPy@kBSuh!E=AO(!W=P#E=Rv>@;rl;MqLg<&5V7_%)*>dgqj`wu1W{t zY2=X^UYk#_~#pYErZX-K6$X3on{wI>1 zw77l|o#lw#->~4-6Ie$Dr~nn90#tws3>C;WJ)I4cjHv(>paM|9z7Hj_Cia2;>A>P6 z0I)&Y4YAJ>z+wqtP3!}afoV{ILDd{FH0a2etgDHAV9-VVWIQKN)|^n(Pe;CZxo8dK zN(HFEqXLuI&aMBi;7{iNM-q2bfC~I81+-bNmkYd7_SVtMS+6bd4cuyOa5KbC!Q$;0 j=m!pwp3eI*>mDrVEV { + Self.remoteMethodCtx('collectionGet', { + description: 'Get pending collections from a worker', + accessType: 'WRITE', + returns: { + type: 'Object', + root: true + }, + http: { + path: `/collectionGet`, + verb: 'POST' + } + }); + + Self.collectionGet = async ctx => { + const userId = ctx.req.accessToken.userId; + const query = `CALL vn.collection_get(?)`; + const [result] = await Self.rawSql(query, [userId]); + + return result; + }; +}; diff --git a/back/methods/collection/collectionNew.js b/back/methods/collection/collectionNew.js new file mode 100644 index 000000000..59830a08b --- /dev/null +++ b/back/methods/collection/collectionNew.js @@ -0,0 +1,120 @@ +module.exports = Self => { + Self.remoteMethodCtx('collectionNew', { + description: 'Make a new collection of tickets', + accessType: 'WRITE', + accepts: [{ + arg: 'collectionFk', + type: 'Number', + required: false, + description: 'The collection id' + }, { + arg: 'sectorFk', + type: 'Number', + required: true, + description: 'The sector of worker' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/collectionNew`, + verb: 'POST' + } + }); + + Self.collectionNew = async(ctx, collectionFk, sectorFk) => { + let query = ''; + + if (!collectionFk) { + const userId = ctx.req.accessToken.userId; + query = `CALL vn.collection_newBeta(?,?)`; + const [result] = await Self.rawSql(query, [sectorFk, userId]); + if (result.length == 0) + throw new Error(`No collections for today`); + + collectionFk = result[0].vCollectionFk; + } + + query = `CALL vn.collectionTicket_get(?)`; + const [tickets] = await Self.rawSql(query, [collectionFk]); + + query = `CALL vn.collectionSale_get(?)`; + const [sales] = await Self.rawSql(query, [collectionFk]); + + query = `CALL vn.collectionPlacement_get(?)`; + const [placements] = await Self.rawSql(query, [collectionFk]); + + return makeCollection(tickets, sales, placements); + }; + + /** + * Returns a collection json + * @param {*} tickets - Request tickets + * @param {*} sales - Request sales + * @param {*} placements - Request placements + * @return {Object} Collection JSON + */ + async function makeCollection(tickets, sales, placements) { + let collection = []; + + for (let i = 0; i < tickets.length; i++) { + let ticket = {}; + ticket['ticketFk'] = tickets[i]['ticketFk']; + ticket['level'] = tickets[i]['level']; + ticket['agencyName'] = tickets[i]['agencyName']; + ticket['warehouseFk'] = tickets[i]['warehouseFk']; + ticket['salesPersonFk'] = tickets[i]['salesPersonFk']; + + let ticketSales = []; + + for (let x = 0; x < sales.length; x++) { + if (sales[x]['ticketFk'] == ticket['ticketFk']) { + let sale = {}; + + sale['ticketFk'] = sales[x]['ticketFk']; + sale['saleFk'] = sales[x]['saleFk']; + sale['itemFk'] = sales[x]['itemFk']; + sale['quantity'] = sales[x]['quantity']; + sale['longName'] = sales[x]['longName']; + sale['size'] = sales[x]['size']; + sale['color'] = sales[x]['color']; + sale['discount'] = sales[x]['discount']; + sale['price'] = sales[x]['price']; + sale['stems'] = sales[x]['stems']; + sale['category'] = sales[x]['category']; + sale['origin'] = sales[x]['origin']; + sale['clientFk'] = sales[x]['clientFk']; + sale['productor'] = sales[x]['productor']; + sale['reserved'] = sales[x]['reserved']; + sale['isPreviousPrepared'] = sales[x]['isPreviousPrepared']; + sale['isPrepared'] = sales[x]['isPrepared']; + sale['isControlled'] = sales[x]['isControlled']; + + let salePlacements = []; + + for (let z = 0; z < placements.length; z++) { + if (placements[z]['saleFk'] == sale['saleFk']) { + let placement = {}; + placement['saleFk'] = placements[z]['saleFk']; + placement['itemFk'] = placements[z]['itemFk']; + placement['placement'] = placements[z]['placement']; + placement['shelving'] = placements[z]['shelving']; + placement['created'] = placements[z]['created']; + placement['visible'] = placements[z]['visible']; + placement['order'] = placements[z]['order']; + placement['grouping'] = placements[z]['grouping']; + salePlacements.push(placement); + } + } + sale['placements'] = salePlacements; + ticketSales.push(sale); + } + } + ticket['sales'] = ticketSales; + collection.push(ticket); + } + + return collection; + } +}; diff --git a/back/methods/collection/getSectors.js b/back/methods/collection/getSectors.js new file mode 100644 index 000000000..c5da7ec13 --- /dev/null +++ b/back/methods/collection/getSectors.js @@ -0,0 +1,20 @@ +module.exports = Self => { + Self.remoteMethodCtx('getSectors', { + description: 'Get all sectors', + accessType: 'WRITE', + returns: { + type: 'Object', + root: true + }, + http: { + path: `/getSectors`, + verb: 'POST' + } + }); + + Self.getSectors = async ctx => { + const query = `CALL vn.sector_get()`; + const [result] = await Self.rawSql(query, []); + return result; + }; +}; diff --git a/back/model-config.json b/back/model-config.json index 50603be3f..872f2239e 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -14,6 +14,9 @@ "Container": { "dataSource": "storage" }, + "Collection": { + "dataSource": "vn" + }, "Chat": { "dataSource": "vn" }, diff --git a/back/models/collection.js b/back/models/collection.js new file mode 100644 index 000000000..2802425a5 --- /dev/null +++ b/back/models/collection.js @@ -0,0 +1,5 @@ +module.exports = Self => { + require('../methods/collection/collectionGet')(Self); + require('../methods/collection/collectionNew')(Self); + require('../methods/collection/getSectors')(Self); +}; diff --git a/back/models/collection.json b/back/models/collection.json new file mode 100644 index 000000000..3e428ef60 --- /dev/null +++ b/back/models/collection.json @@ -0,0 +1,12 @@ +{ + "name": "Collection", + "base": "VnModel", + "acls": [{ + "property": "validations", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} + \ No newline at end of file diff --git a/loopback/.DS_Store b/loopback/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5eff1eaf067fb52e1e272e187642d76f154ecfcf GIT binary patch literal 6148 zcmeHK!EVz)5S>j;>I4uuAhkzdkT^tDT0|&9NNGq9Js=^B-~gz#W2-fFy;1Bmf)L~j z9|3>Br|<=Q2p<4%b{AA9z<~oo(M~k;c4udHz0cWQFA<6UB-$ow5s?dJbeb@~5N>B( zlA7^wqfmWF$_`RF3{x2{MO%kuz%uZ^F~DoLPD7G(hF^94@}_VPdh?qS_2_j<5jCU$ z7++ZH9Q$b@_6m&6Y8V~S~uUQxb0hS*rhYtUobr#%|bL*N#kE2@qp-Y;a-(Qiy+ zI%m5O`}I$;;WQta-Rg5VN|U_kbiRn%nsceX?z&C4dA0e{Kao?v2#QJG55~{A_9!S$ zLQ{SsW%{!mgin)rdf2-DKxRddWbs%fCsB-$7tfL`lGDDNWKpjA@pXgiHr&QxYjZZc zyW4GhJKgTQ?ag*~ZnwQVom=yH!`-;CegEL-?Dd=3+xfc>m=Hu@%T;pC;1BqSLWPiX zf1ITadRG>~3=87S7I{coA>lrLH>U0w3@*&K~!rV}V z8Xf(6Dx5@5qqUX+%RrTZHC=7-`M>}B`+qgb)+_^-ft6xFI0Jvs$CS+3x->aHYdz=@ ql!fC;jVcAk9LK7_NAV_93EDg^0DA^YjqpJ1hk&BN8q2^xW#Buj-=0PQ literal 0 HcmV?d00001 From a4f14e5fdad7db702f337535edf2dc63525ae9b9 Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 23 Mar 2020 10:36:10 +0100 Subject: [PATCH 02/25] collection update sale --- .../collection/collectionUpdateSale.js | 42 +++++++++++++++++++ back/models/collection.js | 1 + 2 files changed, 43 insertions(+) create mode 100644 back/methods/collection/collectionUpdateSale.js diff --git a/back/methods/collection/collectionUpdateSale.js b/back/methods/collection/collectionUpdateSale.js new file mode 100644 index 000000000..4e8775755 --- /dev/null +++ b/back/methods/collection/collectionUpdateSale.js @@ -0,0 +1,42 @@ +module.exports = Self => { + Self.remoteMethodCtx('collectionUpdateSale', { + description: 'Update sale of a collection', + accessType: 'WRITE', + accepts: [{ + arg: 'sale', + type: 'Number', + required: true, + description: 'The sale id' + }, { + arg: 'originalQuantity', + type: 'Number', + required: true, + description: 'The quantity to sale' + }, { + arg: 'ticketFk', + type: 'Number', + required: true, + description: 'The ticket id' + }, { + arg: 'stateFk', + type: 'Number', + required: true, + description: 'The state id' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/collectionUpdateSale`, + verb: 'POST' + } + }); + + Self.collectionUpdateSale = async(ctx, sale, originalQuantity, ticketFk, stateFk) => { + const userId = ctx.req.accessToken.userId; + + query = `vn.collection_updateSale(?,?,?,?,?)`; + return await Self.rawSql(query, [sale, originalQuantity, userId, stateFk, ticketFk]); + }; +}; diff --git a/back/models/collection.js b/back/models/collection.js index 2802425a5..9f944d72f 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -2,4 +2,5 @@ module.exports = Self => { require('../methods/collection/collectionGet')(Self); require('../methods/collection/collectionNew')(Self); require('../methods/collection/getSectors')(Self); + require('../methods/collection/collectionUpdateSale')(Self); }; From c7a5d94ed0ebc51bee2ce89f291168ec3f3a2f12 Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 23 Mar 2020 13:26:45 +0100 Subject: [PATCH 03/25] faults --- back/methods/collection/collectionFaults.js | 35 +++++++++++++++++++++ back/methods/collection/collectionNew.js | 3 ++ back/models/collection.js | 1 + 3 files changed, 39 insertions(+) create mode 100644 back/methods/collection/collectionFaults.js diff --git a/back/methods/collection/collectionFaults.js b/back/methods/collection/collectionFaults.js new file mode 100644 index 000000000..b39e9f2d2 --- /dev/null +++ b/back/methods/collection/collectionFaults.js @@ -0,0 +1,35 @@ +module.exports = Self => { + Self.remoteMethodCtx('collectionFaults', { + description: 'Update sale of a collection', + accessType: 'WRITE', + accepts: [{ + arg: 'shelvingFk', + type: 'Number', + required: true, + description: 'The sale id' + }, { + arg: 'quantity', + type: 'Number', + required: true, + description: 'The quantity to sale' + }, { + arg: 'itemFk', + type: 'Number', + required: true, + description: 'The ticket id' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/collectionFaults`, + verb: 'POST' + } + }); + + Self.collectionFaults = async(ctx, shelvingFk, quantity, itemFk) => { + query = `vn.collection_faults(?,?,?)`; + return await Self.rawSql(query, [shelvingFk, quantity, itemFk]); + }; +}; diff --git a/back/methods/collection/collectionNew.js b/back/methods/collection/collectionNew.js index 59830a08b..6e248f640 100644 --- a/back/methods/collection/collectionNew.js +++ b/back/methods/collection/collectionNew.js @@ -45,6 +45,9 @@ module.exports = Self => { query = `CALL vn.collectionPlacement_get(?)`; const [placements] = await Self.rawSql(query, [collectionFk]); + query = `CALL vn.collectionSticker_print(?,?)`; + // await Self.rawSql(query, [collectionFk, sectorFk]); + return makeCollection(tickets, sales, placements); }; diff --git a/back/models/collection.js b/back/models/collection.js index 9f944d72f..aad0b4196 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -3,4 +3,5 @@ module.exports = Self => { require('../methods/collection/collectionNew')(Self); require('../methods/collection/getSectors')(Self); require('../methods/collection/collectionUpdateSale')(Self); + require('../methods/collection/collectionFaults')(Self); }; From 52f97e1decd0e6408f9b14dcb28fb271a8c65fdf Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 23 Mar 2020 15:22:48 +0100 Subject: [PATCH 04/25] sacadores --- back/methods/collection/collectionFaults.js | 6 +++--- back/methods/collection/collectionNew.js | 17 +++++++++++------ back/methods/collection/collectionUpdateSale.js | 2 +- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/back/methods/collection/collectionFaults.js b/back/methods/collection/collectionFaults.js index b39e9f2d2..ac5186575 100644 --- a/back/methods/collection/collectionFaults.js +++ b/back/methods/collection/collectionFaults.js @@ -4,9 +4,9 @@ module.exports = Self => { accessType: 'WRITE', accepts: [{ arg: 'shelvingFk', - type: 'Number', + type: 'String', required: true, - description: 'The sale id' + description: 'The shalving id' }, { arg: 'quantity', type: 'Number', @@ -29,7 +29,7 @@ module.exports = Self => { }); Self.collectionFaults = async(ctx, shelvingFk, quantity, itemFk) => { - query = `vn.collection_faults(?,?,?)`; + query = `CALL vn.collection_faults(?,?,?)`; return await Self.rawSql(query, [shelvingFk, quantity, itemFk]); }; }; diff --git a/back/methods/collection/collectionNew.js b/back/methods/collection/collectionNew.js index 6e248f640..9a3020bf8 100644 --- a/back/methods/collection/collectionNew.js +++ b/back/methods/collection/collectionNew.js @@ -12,6 +12,11 @@ module.exports = Self => { type: 'Number', required: true, description: 'The sector of worker' + }, { + arg: 'vWagons', + type: 'Number', + required: true, + description: 'The number of wagons' }], returns: { type: 'Object', @@ -23,13 +28,13 @@ module.exports = Self => { } }); - Self.collectionNew = async(ctx, collectionFk, sectorFk) => { + Self.collectionNew = async(ctx, collectionFk, sectorFk, vWagons) => { let query = ''; if (!collectionFk) { const userId = ctx.req.accessToken.userId; - query = `CALL vn.collection_newBeta(?,?)`; - const [result] = await Self.rawSql(query, [sectorFk, userId]); + query = `CALL vn.collectionTrain_newBeta(?,?,?)`; + const [result] = await Self.rawSql(query, [sectorFk, vWagons, userId]); if (result.length == 0) throw new Error(`No collections for today`); @@ -48,7 +53,7 @@ module.exports = Self => { query = `CALL vn.collectionSticker_print(?,?)`; // await Self.rawSql(query, [collectionFk, sectorFk]); - return makeCollection(tickets, sales, placements); + return makeCollection(tickets, sales, placements, collectionFk); }; /** @@ -58,7 +63,7 @@ module.exports = Self => { * @param {*} placements - Request placements * @return {Object} Collection JSON */ - async function makeCollection(tickets, sales, placements) { + async function makeCollection(tickets, sales, placements, collectionFk) { let collection = []; for (let i = 0; i < tickets.length; i++) { @@ -74,7 +79,7 @@ module.exports = Self => { for (let x = 0; x < sales.length; x++) { if (sales[x]['ticketFk'] == ticket['ticketFk']) { let sale = {}; - + sale['collectionFk'] = collectionFk; sale['ticketFk'] = sales[x]['ticketFk']; sale['saleFk'] = sales[x]['saleFk']; sale['itemFk'] = sales[x]['itemFk']; diff --git a/back/methods/collection/collectionUpdateSale.js b/back/methods/collection/collectionUpdateSale.js index 4e8775755..7204dad22 100644 --- a/back/methods/collection/collectionUpdateSale.js +++ b/back/methods/collection/collectionUpdateSale.js @@ -36,7 +36,7 @@ module.exports = Self => { Self.collectionUpdateSale = async(ctx, sale, originalQuantity, ticketFk, stateFk) => { const userId = ctx.req.accessToken.userId; - query = `vn.collection_updateSale(?,?,?,?,?)`; + query = `CALL vn.collection_updateSale(?,?,?,?,?)`; return await Self.rawSql(query, [sale, originalQuantity, userId, stateFk, ticketFk]); }; }; From b9c6f76c47432cfc26d203c9b2a4d752b636df41 Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 23 Mar 2020 15:34:13 +0100 Subject: [PATCH 05/25] print --- back/methods/collection/collectionNew.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/back/methods/collection/collectionNew.js b/back/methods/collection/collectionNew.js index 9a3020bf8..d22a0b7fe 100644 --- a/back/methods/collection/collectionNew.js +++ b/back/methods/collection/collectionNew.js @@ -51,7 +51,7 @@ module.exports = Self => { const [placements] = await Self.rawSql(query, [collectionFk]); query = `CALL vn.collectionSticker_print(?,?)`; - // await Self.rawSql(query, [collectionFk, sectorFk]); + await Self.rawSql(query, [collectionFk, sectorFk]); return makeCollection(tickets, sales, placements, collectionFk); }; @@ -61,6 +61,7 @@ module.exports = Self => { * @param {*} tickets - Request tickets * @param {*} sales - Request sales * @param {*} placements - Request placements + * @param {*} collectionFk - Request placements * @return {Object} Collection JSON */ async function makeCollection(tickets, sales, placements, collectionFk) { From 7d6a33d79a525a38935db22f1c32bfdc87a1f27d Mon Sep 17 00:00:00 2001 From: Ainki Date: Thu, 26 Mar 2020 13:12:59 +0100 Subject: [PATCH 06/25] change some names an methods --- back/methods/collection/collectionFaults.js | 4 +- .../collection/collectionUpdateSale.js | 42 --------- .../{collectionGet.js => getCollection.js} | 10 +-- back/methods/collection/getSectors.js | 4 +- .../{collectionNew.js => newCollection.js} | 10 ++- .../collection/updateCollectionSale.js | 89 +++++++++++++++++++ back/models/collection.js | 6 +- 7 files changed, 108 insertions(+), 57 deletions(-) delete mode 100644 back/methods/collection/collectionUpdateSale.js rename back/methods/collection/{collectionGet.js => getCollection.js} (69%) rename back/methods/collection/{collectionNew.js => newCollection.js} (93%) create mode 100644 back/methods/collection/updateCollectionSale.js diff --git a/back/methods/collection/collectionFaults.js b/back/methods/collection/collectionFaults.js index ac5186575..395c7e581 100644 --- a/back/methods/collection/collectionFaults.js +++ b/back/methods/collection/collectionFaults.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('collectionFaults', { + Self.remoteMethod('collectionFaults', { description: 'Update sale of a collection', accessType: 'WRITE', accepts: [{ @@ -28,7 +28,7 @@ module.exports = Self => { } }); - Self.collectionFaults = async(ctx, shelvingFk, quantity, itemFk) => { + Self.collectionFaults = async(shelvingFk, quantity, itemFk) => { query = `CALL vn.collection_faults(?,?,?)`; return await Self.rawSql(query, [shelvingFk, quantity, itemFk]); }; diff --git a/back/methods/collection/collectionUpdateSale.js b/back/methods/collection/collectionUpdateSale.js deleted file mode 100644 index 7204dad22..000000000 --- a/back/methods/collection/collectionUpdateSale.js +++ /dev/null @@ -1,42 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('collectionUpdateSale', { - description: 'Update sale of a collection', - accessType: 'WRITE', - accepts: [{ - arg: 'sale', - type: 'Number', - required: true, - description: 'The sale id' - }, { - arg: 'originalQuantity', - type: 'Number', - required: true, - description: 'The quantity to sale' - }, { - arg: 'ticketFk', - type: 'Number', - required: true, - description: 'The ticket id' - }, { - arg: 'stateFk', - type: 'Number', - required: true, - description: 'The state id' - }], - returns: { - type: 'Object', - root: true - }, - http: { - path: `/collectionUpdateSale`, - verb: 'POST' - } - }); - - Self.collectionUpdateSale = async(ctx, sale, originalQuantity, ticketFk, stateFk) => { - const userId = ctx.req.accessToken.userId; - - query = `CALL vn.collection_updateSale(?,?,?,?,?)`; - return await Self.rawSql(query, [sale, originalQuantity, userId, stateFk, ticketFk]); - }; -}; diff --git a/back/methods/collection/collectionGet.js b/back/methods/collection/getCollection.js similarity index 69% rename from back/methods/collection/collectionGet.js rename to back/methods/collection/getCollection.js index ff98c55d5..caf9cc521 100644 --- a/back/methods/collection/collectionGet.js +++ b/back/methods/collection/getCollection.js @@ -1,18 +1,18 @@ module.exports = Self => { - Self.remoteMethodCtx('collectionGet', { + Self.remoteMethodCtx('getCollection', { description: 'Get pending collections from a worker', - accessType: 'WRITE', + accessType: 'READ', returns: { type: 'Object', root: true }, http: { - path: `/collectionGet`, - verb: 'POST' + path: `/getCollection`, + verb: 'GET' } }); - Self.collectionGet = async ctx => { + Self.getCollection = async ctx => { const userId = ctx.req.accessToken.userId; const query = `CALL vn.collection_get(?)`; const [result] = await Self.rawSql(query, [userId]); diff --git a/back/methods/collection/getSectors.js b/back/methods/collection/getSectors.js index c5da7ec13..d844e5097 100644 --- a/back/methods/collection/getSectors.js +++ b/back/methods/collection/getSectors.js @@ -1,14 +1,14 @@ module.exports = Self => { Self.remoteMethodCtx('getSectors', { description: 'Get all sectors', - accessType: 'WRITE', + accessType: 'READ', returns: { type: 'Object', root: true }, http: { path: `/getSectors`, - verb: 'POST' + verb: 'GET' } }); diff --git a/back/methods/collection/collectionNew.js b/back/methods/collection/newCollection.js similarity index 93% rename from back/methods/collection/collectionNew.js rename to back/methods/collection/newCollection.js index d22a0b7fe..31e419b67 100644 --- a/back/methods/collection/collectionNew.js +++ b/back/methods/collection/newCollection.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('collectionNew', { + Self.remoteMethodCtx('newCollection', { description: 'Make a new collection of tickets', accessType: 'WRITE', accepts: [{ @@ -23,12 +23,12 @@ module.exports = Self => { root: true }, http: { - path: `/collectionNew`, + path: `/newCollection`, verb: 'POST' } }); - Self.collectionNew = async(ctx, collectionFk, sectorFk, vWagons) => { + Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => { let query = ''; if (!collectionFk) { @@ -85,6 +85,10 @@ module.exports = Self => { sale['saleFk'] = sales[x]['saleFk']; sale['itemFk'] = sales[x]['itemFk']; sale['quantity'] = sales[x]['quantity']; + if (sales[x]['quantityPicked'] != null) + sale['quantityPicked'] = sales[x]['quantityPicked']; + else + sale['quantityPicked'] = 0; sale['longName'] = sales[x]['longName']; sale['size'] = sales[x]['size']; sale['color'] = sales[x]['color']; diff --git a/back/methods/collection/updateCollectionSale.js b/back/methods/collection/updateCollectionSale.js new file mode 100644 index 000000000..01575c972 --- /dev/null +++ b/back/methods/collection/updateCollectionSale.js @@ -0,0 +1,89 @@ +module.exports = Self => { + Self.remoteMethodCtx('updateCollectionSale', { + description: 'Update sale of a collection', + accessType: 'WRITE', + accepts: [{ + arg: 'sale', + type: 'Number', + required: true, + description: 'The sale id' + }, { + arg: 'originalQuantity', + type: 'Number', + required: true, + description: 'The quantity to sale' + }, + { + arg: 'quantity', + type: 'Number', + required: true, + description: 'The quantity to picked' + }, + { + arg: 'quantityPicked', + type: 'Number', + required: true, + description: 'The quantity to picked' + }, { + arg: 'ticketFk', + type: 'Number', + required: true, + description: 'The ticket id' + }, { + arg: 'stateFk', + type: 'Number', + required: true, + description: 'The state id' + }, { + arg: 'isNicho', + type: 'Boolean', + required: true, + description: 'Determine if sale is picked from nicho or not' + }, { + arg: 'shelvingFk', + type: 'String', + required: false, + description: 'The shelving id' + }, { + arg: 'itemFk', + type: 'Number', + required: true, + description: 'The item id' + }, { + arg: 'sectorFk', + type: 'Number', + required: true, + description: 'The sector id' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/updateCollectionSale`, + verb: 'POST' + } + }); + + Self.updateCollectionSale = async(ctx, sale, originalQuantity, quantity, quantityPicked, ticketFk, stateFk, isNicho, shelvingFk, itemFk, sectorFk) => { + const userId = ctx.req.accessToken.userId; + + if (originalQuantity == quantity) { + query = `CALL vn.collection_updateSale(?,?,?,?,?)`; + await Self.rawSql(query, [sale, originalQuantity, userId, stateFk, ticketFk]); + } + + if (!isNicho) { + query = `CALL vn.collection_faults(?,?,?)`; + await Self.rawSql(query, [shelvingFk, quantityPicked, itemFk]); + } else { + query = `CALL vn.sector_getWarehouse(?)`; + const [result] = await Self.rawSql(query, [sectorFk]); + + query = `CALL vn.itemPlacementSave(?,?,?)`; + await Self.rawSql(query, [shelvingFk, quantityPicked, result[0]['warehouseFk']]); + } + query = `CALL vn.sale_updateOriginalQuantity(?,?)`; + return await Self.rawSql(query, [sale, quantity]); + }; +}; diff --git a/back/models/collection.js b/back/models/collection.js index aad0b4196..d3670d56b 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -1,7 +1,7 @@ module.exports = Self => { - require('../methods/collection/collectionGet')(Self); - require('../methods/collection/collectionNew')(Self); + require('../methods/collection/getCollection')(Self); + require('../methods/collection/newCollection')(Self); require('../methods/collection/getSectors')(Self); - require('../methods/collection/collectionUpdateSale')(Self); + require('../methods/collection/updateCollectionSale')(Self); require('../methods/collection/collectionFaults')(Self); }; From 3f1039f6d7a68a5e62a7a3f909bf86050d5dfdd5 Mon Sep 17 00:00:00 2001 From: Ainki Date: Thu, 26 Mar 2020 19:10:09 +0100 Subject: [PATCH 07/25] spec --- back/methods/collection/getSectors.js | 6 +++--- back/methods/collection/spec/collectionFauls.spec.js | 8 ++++++++ back/methods/collection/spec/getCollection.spec.js | 10 ++++++++++ back/methods/collection/spec/getSectors.spec.js | 9 +++++++++ back/methods/collection/spec/newCollection.spec.js | 10 ++++++++++ .../collection/spec/updateCollectionSale.spec.js | 7 +++++++ 6 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 back/methods/collection/spec/collectionFauls.spec.js create mode 100644 back/methods/collection/spec/getCollection.spec.js create mode 100644 back/methods/collection/spec/getSectors.spec.js create mode 100644 back/methods/collection/spec/newCollection.spec.js create mode 100644 back/methods/collection/spec/updateCollectionSale.spec.js diff --git a/back/methods/collection/getSectors.js b/back/methods/collection/getSectors.js index d844e5097..12ad0dc06 100644 --- a/back/methods/collection/getSectors.js +++ b/back/methods/collection/getSectors.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('getSectors', { + Self.remoteMethod('getSectors', { description: 'Get all sectors', accessType: 'READ', returns: { @@ -12,9 +12,9 @@ module.exports = Self => { } }); - Self.getSectors = async ctx => { + Self.getSectors = async() => { const query = `CALL vn.sector_get()`; - const [result] = await Self.rawSql(query, []); + const [result] = await Self.rawSql(query); return result; }; }; diff --git a/back/methods/collection/spec/collectionFauls.spec.js b/back/methods/collection/spec/collectionFauls.spec.js new file mode 100644 index 000000000..0df234bfd --- /dev/null +++ b/back/methods/collection/spec/collectionFauls.spec.js @@ -0,0 +1,8 @@ + +describe('collectionFaults()', () => { + it('return shelving afected', async() => { + let val = 2; + + expect(val).toBeGreaterThan(1); + }); +}); diff --git a/back/methods/collection/spec/getCollection.spec.js b/back/methods/collection/spec/getCollection.spec.js new file mode 100644 index 000000000..b8a92285f --- /dev/null +++ b/back/methods/collection/spec/getCollection.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('getCollection()', () => { + it('return list of collection', async() => { + let ctx = {req: {accessToken: {userId: 1}}}; + let response = await app.models.Collection.getCollection(ctx); + + expect(response.length).toEqual(0); + }); +}); diff --git a/back/methods/collection/spec/getSectors.spec.js b/back/methods/collection/spec/getSectors.spec.js new file mode 100644 index 000000000..4ba288c01 --- /dev/null +++ b/back/methods/collection/spec/getSectors.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('getSectors()', () => { + it('return list of sectors', async() => { + let response = await app.models.Collection.getSectors(); + + expect(response.length).toBeGreaterThan(0); + }); +}); diff --git a/back/methods/collection/spec/newCollection.spec.js b/back/methods/collection/spec/newCollection.spec.js new file mode 100644 index 000000000..4bf3f7945 --- /dev/null +++ b/back/methods/collection/spec/newCollection.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('newCollection()', () => { + it('return a new collection', async() => { + let ctx = {req: {accessToken: {userId: 1}}}; + let response = await app.models.Collection.newCollection(ctx, 500, 1, 1); + + expect(response.length).toBeGreaterThan(0); + }); +}); diff --git a/back/methods/collection/spec/updateCollectionSale.spec.js b/back/methods/collection/spec/updateCollectionSale.spec.js new file mode 100644 index 000000000..bd4d0fb78 --- /dev/null +++ b/back/methods/collection/spec/updateCollectionSale.spec.js @@ -0,0 +1,7 @@ +describe('updateCollectionSale()', () => { + it('return a collection updated', async() => { + let val = 2; + + expect(val).toBeGreaterThan(1); + }); +}); From 42f3bfb86dec4f0451ef37ae13e0dd6c5a0469c4 Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 30 Mar 2020 14:28:29 +0200 Subject: [PATCH 08/25] test, fitxures and changes --- .../collection/spec/collectionFauls.spec.js | 7 +- .../collection/spec/getCollection.spec.js | 5 +- .../collection/spec/getSectors.spec.js | 2 + .../collection/spec/newCollection.spec.js | 5 +- .../spec/updateCollectionSale.spec.js | 13 +- .../00-collectionPlacement_get.sql | 108 + .../00-collection_faults.sql | 39 + .../00-collection_updateSale.sql | 42 + .../00-coolerPathDetail.sql | 13 + .../00-sale_updateOriginalQuantity.sql | 15 + .../00-sector_getWarehouse.sql | 14 + db/dump/fixtures.sql | 25 +- db/dump/structure.sql | 2076 ++++++++--------- 13 files changed, 1314 insertions(+), 1050 deletions(-) create mode 100644 db/changes/10162-postValentineDay/00-collectionPlacement_get.sql create mode 100644 db/changes/10162-postValentineDay/00-collection_faults.sql create mode 100644 db/changes/10162-postValentineDay/00-collection_updateSale.sql create mode 100644 db/changes/10162-postValentineDay/00-coolerPathDetail.sql create mode 100644 db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql create mode 100644 db/changes/10162-postValentineDay/00-sector_getWarehouse.sql diff --git a/back/methods/collection/spec/collectionFauls.spec.js b/back/methods/collection/spec/collectionFauls.spec.js index 0df234bfd..210dcdf63 100644 --- a/back/methods/collection/spec/collectionFauls.spec.js +++ b/back/methods/collection/spec/collectionFauls.spec.js @@ -1,8 +1,9 @@ - +const app = require('vn-loopback/server/server'); describe('collectionFaults()', () => { it('return shelving afected', async() => { - let val = 2; + let response = await app.models.Collection.collectionFaults('UXN', 0, 1); - expect(val).toBeGreaterThan(1); + expect(response.length).toBeGreaterThan(0); + expect(response[0][0].shelvingFk).toEqual('UXN'); }); }); diff --git a/back/methods/collection/spec/getCollection.spec.js b/back/methods/collection/spec/getCollection.spec.js index b8a92285f..44c7af62f 100644 --- a/back/methods/collection/spec/getCollection.spec.js +++ b/back/methods/collection/spec/getCollection.spec.js @@ -2,9 +2,10 @@ const app = require('vn-loopback/server/server'); describe('getCollection()', () => { it('return list of collection', async() => { - let ctx = {req: {accessToken: {userId: 1}}}; + let ctx = {req: {accessToken: {userId: 106}}}; let response = await app.models.Collection.getCollection(ctx); - expect(response.length).toEqual(0); + expect(response.length).toBeGreaterThan(0); + expect(response[0].collectionFk).toEqual(1); }); }); diff --git a/back/methods/collection/spec/getSectors.spec.js b/back/methods/collection/spec/getSectors.spec.js index 4ba288c01..d453220a0 100644 --- a/back/methods/collection/spec/getSectors.spec.js +++ b/back/methods/collection/spec/getSectors.spec.js @@ -5,5 +5,7 @@ describe('getSectors()', () => { let response = await app.models.Collection.getSectors(); expect(response.length).toBeGreaterThan(0); + expect(response[0].id).toEqual(1); + expect(response[0].description).toEqual('First sector'); }); }); diff --git a/back/methods/collection/spec/newCollection.spec.js b/back/methods/collection/spec/newCollection.spec.js index 4bf3f7945..bd574db0f 100644 --- a/back/methods/collection/spec/newCollection.spec.js +++ b/back/methods/collection/spec/newCollection.spec.js @@ -2,9 +2,10 @@ const app = require('vn-loopback/server/server'); describe('newCollection()', () => { it('return a new collection', async() => { - let ctx = {req: {accessToken: {userId: 1}}}; - let response = await app.models.Collection.newCollection(ctx, 500, 1, 1); + let ctx = {req: {accessToken: {userId: 106}}}; + let response = await app.models.Collection.newCollection(ctx, 1, 1, 1); expect(response.length).toBeGreaterThan(0); + expect(response[0].ticketFk).toEqual(1); }); }); diff --git a/back/methods/collection/spec/updateCollectionSale.spec.js b/back/methods/collection/spec/updateCollectionSale.spec.js index bd4d0fb78..4695f6eec 100644 --- a/back/methods/collection/spec/updateCollectionSale.spec.js +++ b/back/methods/collection/spec/updateCollectionSale.spec.js @@ -1,7 +1,12 @@ -describe('updateCollectionSale()', () => { - it('return a collection updated', async() => { - let val = 2; +const app = require('vn-loopback/server/server'); - expect(val).toBeGreaterThan(1); +describe('updateCollectionSale()', () => { + it('return a new collection', async() => { + let ctx = {req: {accessToken: {userId: 106}}}; + let response = await app.models.Collection.updateCollectionSale(ctx, 1, 5, 5, 5, 1, 4, false, 'UXN', 1, 1); + + expect(response.length).toBeGreaterThan(0); + expect(response[0][0].id).toEqual(1); + expect(response[0][0].quantity).toEqual(5); }); }); diff --git a/db/changes/10162-postValentineDay/00-collectionPlacement_get.sql b/db/changes/10162-postValentineDay/00-collectionPlacement_get.sql new file mode 100644 index 000000000..d89f6a801 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-collectionPlacement_get.sql @@ -0,0 +1,108 @@ +DROP procedure IF EXISTS `vn`.`collectionPlacement_get`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`collectionPlacement_get`(vCollectionFk INT) +BEGIN + + DECLARE vCalcFk INT; + DECLARE vWarehouseFk INT; + DECLARE vWarehouseAliasFk INT; + + SELECT t.warehouseFk, w.aliasFk + INTO vWarehouseFk, vWarehouseAliasFk + FROM vn.ticket t + JOIN vn.ticketCollection tc ON tc.ticketFk = t.id + JOIN vn.warehouse w ON w.id = t.warehouseFk + WHERE tc.collectionFk = vCollectionFk + LIMIT 1; + + CALL cache.visible_refresh(vCalcFk,FALSE,vWarehouseFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.parked; + CREATE TEMPORARY TABLE tmp.parked + ENGINE MEMORY + SELECT s.itemFk, 0 as quantity + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk; + + UPDATE tmp.parked pk + JOIN ( SELECT itemFk, sum(visible) as visible + FROM vn.itemShelvingStock iss + JOIN vn.warehouse w ON w.id = iss.warehouseFk + WHERE w.aliasFk = vWarehouseAliasFk + GROUP BY iss.itemFk ) iss ON iss.itemFk = pk.itemFk + SET pk.quantity = iss.visible; + + DROP TEMPORARY TABLE IF EXISTS tmp.`grouping`; + CREATE TEMPORARY TABLE tmp.`grouping` + ENGINE MEMORY + SELECT itemFk, `grouping` + FROM ( + SELECT itemFk, + CASE groupingMode + WHEN 0 THEN 1 + WHEN 2 THEN packing + ELSE `grouping` + END AS `grouping` + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseInFk = vWarehouseFk + AND landed BETWEEN (SELECT inventoried FROM vn.config LIMIT 1) AND CURDATE() + AND b.isIgnored = FALSE + ORDER BY tr.landed DESC + ) sub + GROUP BY sub.itemFk ; + + DROP TEMPORARY TABLE IF EXISTS tmp.grouping2; + CREATE TEMPORARY TABLE tmp.grouping2 + ENGINE MEMORY + SELECT * FROM tmp.`grouping`; + + + SELECT s.id as saleFk, s.itemFk, + p.code COLLATE utf8_general_ci as placement , + sh.code COLLATE utf8_general_ci as shelving, + ish.created, + ish.visible, + 0 as `order`, + IF(sc.isPreviousPreparedByPacking, ish.packing, g.`grouping`) as `grouping` + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector sc ON sc.id = p.sectorFk + JOIN vn.warehouse w ON w.id = sc.warehouseFk + JOIN tmp.`grouping` g ON g.itemFk = s.itemFk + WHERE tc.collectionFk = vCollectionFk + AND w.aliasFk = vWarehouseAliasFk + AND ish.visible > 0 + UNION ALL + SELECT s.id as saleFk, s.itemFk, + ip.code COLLATE utf8_general_ci as placement, + '' COLLATE latin1_general_ci as shelving, + modificationDate as created, + v.visible - p.quantity as visible, + 0 as `order`, + g.`grouping` + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.itemPlacement ip ON ip.itemFk = s.itemFk AND ip.warehouseFk = vWarehouseFk + JOIN tmp.parked p ON p.itemFk = s.itemFk + JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vCalcFk + LEFT JOIN tmp.grouping2 g ON g.itemFk = s.itemFk + WHERE tc.collectionFk = vCollectionFk + AND v.visible - p.quantity > 0; + + DROP TEMPORARY TABLE + tmp.parked, + tmp.`grouping`, + tmp.grouping2; +END + + +$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-collection_faults.sql b/db/changes/10162-postValentineDay/00-collection_faults.sql new file mode 100644 index 000000000..5faa42ca4 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-collection_faults.sql @@ -0,0 +1,39 @@ +DROP procedure IF EXISTS `vn`.`collection_faults`; + +DELIMITER $$ + +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`collection_faults`( + vShelvingFk VARCHAR(10), + vQuantity INT, + vItemFk INT) +BEGIN + DECLARE vQuantityTotal INT DEFAULT 0; + DECLARE vshelve VARCHAR(2); + DECLARE vdeep INT(11); + DECLARE vpriority INT(11); + DECLARE vgrouping SMALLINT(5); + DECLARE vpacking INT(11); + DECLARE vpackagingFk VARCHAR(10); + DECLARE vlevel VARCHAR(45); + DECLARE vuserFk INT(10); + + + SELECT SUM(quantity),shelve,deep,priority,`grouping`,packing,packagingFk,`level`,userFk + INTO vQuantityTotal,vshelve,vdeep,vpriority,vgrouping,vpacking,vpackagingFk,vlevel,vuserFk + FROM vn.itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk + GROUP BY itemFk; + + SELECT vQuantityTotal - vQuantity INTO vQuantityTotal; + + DELETE FROM vn.itemShelving WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk; + + INSERT INTO vn.itemShelving (itemFk, shelvingFk,shelve,deep,quantity,visible,available,priority,`grouping`,packing,packagingFk,`level`,userFk ) + VALUES (vItemFk,vShelvingFk,vshelve,vdeep,vQuantityTotal,vQuantityTotal,vQuantityTotal,vpriority,vgrouping,vpacking,vpackagingFk,vlevel,vuserFk ); + + SELECT * FROM vn.itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk; + +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-collection_updateSale.sql b/db/changes/10162-postValentineDay/00-collection_updateSale.sql new file mode 100644 index 000000000..cce8f4ff5 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-collection_updateSale.sql @@ -0,0 +1,42 @@ +DROP procedure IF EXISTS `vn`.`collection_updateSale`; + + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`collection_updateSale`( + vSaleFk INT, + vOriginalQuantity INT, + vWorkerFk INT, + vStateFk INT, + vTicketFk INT) +BEGIN + + DECLARE vNumPrepared INT; + DECLARE vNumTotal INT; + + REPLACE INTO vn.saleTracking(saleFk,isChecked, originalQuantity, workerFk, actionFk,stateFk) + VALUES(vSaleFk,1,vOriginalQuantity,vWorkerFk,vStateFk,vStateFk); + + UPDATE vn.sale SET isPicked = 1 + WHERE id = vSaleFk; + + SELECT COUNT(s.id) INTO vNumPrepared + FROM vn.sale s + WHERE s.ticketFk = vTicketFk AND s.isPicked = 1; + + SELECT COUNT(s.id) INTO vNumTotal + FROM vn.sale s + WHERE s.ticketFk = vTicketFk; + + IF vNumPrepared = vNumTotal THEN + + INSERT INTO vncontrol.inter + SET state_id = vStateFk, Id_Ticket = vTicketFk, Id_Trabajador = vWorkerFk; + + CALL vn.collection_update(vTicketFk); + + END IF; + + +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-coolerPathDetail.sql b/db/changes/10162-postValentineDay/00-coolerPathDetail.sql new file mode 100644 index 000000000..7d3006544 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-coolerPathDetail.sql @@ -0,0 +1,13 @@ +/*DROP view IF EXISTS `vn`.`coolerPathDetail`; + +CREATE + ALGORITHM = UNDEFINED + DEFINER = `root`@`%` + SQL SECURITY DEFINER +VIEW `vn`.`coolerPathDetail` AS + SELECT + `c`.`cooler_path_detail_id` AS `id`, + `c`.`cooler_path_id` AS `coolerPathFk`, + `c`.`pasillo` AS `hallway` + FROM + `vn2008`.`cooler_path_detail` `c`*/ \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql b/db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql new file mode 100644 index 000000000..debdd3ac2 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql @@ -0,0 +1,15 @@ +DROP procedure IF EXISTS `vn`.`sale_updateOriginalQuantity`; + +DELIMITER $$ + +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`sale_updateOriginalQuantity`(vSale INT, vQuantity INT) +proc: BEGIN + +UPDATE vn.sale SET originalQuantity = vQuantity +WHERE id = vSale; + +SELECT * FROM vn.sale WHERE id = vSale; + +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-sector_getWarehouse.sql b/db/changes/10162-postValentineDay/00-sector_getWarehouse.sql new file mode 100644 index 000000000..90611b559 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-sector_getWarehouse.sql @@ -0,0 +1,14 @@ +DROP procedure IF EXISTS `vn`.`sector_getWarehouse`; + +DELIMITER $$ + +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`sector_getWarehouse`(vSectorFk INT) +BEGIN + + SELECT s.warehouseFk + FROM vn.sector s + WHERE s.id = vSectorFk; + +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 7b2fd1cae..fbe33159a 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -21,7 +21,7 @@ INSERT INTO `vn`.`bionicConfig` (`generalInflationCoeficient`, `minimumDensityVo (1.30, 167.00, 138000, 71); INSERT INTO `vn`.`chatConfig` (`host`, `api`) - VALUES + VALUES ('https://chat.verdnatura.es', 'https://chat.verdnatura.es/api/v1'); INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`) @@ -954,6 +954,29 @@ INSERT INTO `vn`.`itemPlacement`(`id`, `itemFk`, `warehouseFk`, `code`) (3, 1, 3, 'A3'), (4, 2, 1, 'A4'); + +INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`) + VALUES + (1, 106, 5), + (2, 106, 14); + +INSERT INTO `vn`.`parking` (`column`, `row`, `sectorFk`, `code`, `pickingOrder`) + VALUES + ('100', '01', 1, '100-01', 1); + +INSERT INTO `vn`.`shelving` (`code`, `parkingFk`, `priority`, `userFk`) + VALUES + ('UXN', 1, 1, 106); + +INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `shelve`, `deep`, `quantity`, `visible`, `available`, `grouping`, `packing`, `level`, `userFk`) + VALUES + (1, 'UXN', 'A', 2, 12, 12, 12, 12, 12, 1, 106); + +INSERT INTO `vn`.`ticketCollection` (`ticketFk`, `collectionFk`, `level`) + VALUES + (1, 1, 1); + + INSERT INTO `edi`.`genus`(`genus_id`, `latin_genus_name`, `entry_date`, `expiry_date`, `change_date_time`) VALUES (1, 'Abelia' , CURDATE(), NULL, CURDATE()), diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 8e783c833..2a1a168d7 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -4055,16 +4055,16 @@ BEGIN * La tabla mana_spellers es una caché * */ - - UPDATE mana_spellers me - JOIN - (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual - FROM bs.vendedores - WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) - GROUP BY Id_Trabajador - ) lastYearSales USING(Id_Trabajador) - SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; - + + UPDATE mana_spellers me + JOIN + (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual + FROM bs.vendedores + WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) + GROUP BY Id_Trabajador + ) lastYearSales USING(Id_Trabajador) + SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6703,9 +6703,9 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cacheCalc_clean`() -BEGIN - DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); - DELETE FROM cache_calc WHERE expires < vCleanTime; +BEGIN + DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); + DELETE FROM cache_calc WHERE expires < vCleanTime; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6723,27 +6723,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` 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 */ ; @@ -6761,88 +6761,88 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` 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 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 - INTO v_cache_id, v_calc, v_expires - 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 - 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 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 + INTO v_cache_id, v_calc, v_expires + 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 + 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 */ ; @@ -6860,24 +6860,24 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_unlock`(IN `v_calc` INT) -proc: BEGIN - DECLARE v_cache_name VARCHAR(50); - DECLARE v_params VARCHAR(100); - - IF v_calc IS NULL THEN - LEAVE proc; - END IF; - - 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; - - DELETE FROM cache_calc WHERE id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +proc: BEGIN + DECLARE v_cache_name VARCHAR(50); + DECLARE v_params VARCHAR(100); + + IF v_calc IS NULL THEN + LEAVE proc; + END IF; + + 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; + + DELETE FROM cache_calc WHERE 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 */ ; @@ -6896,9 +6896,9 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_clean`() NO SQL -BEGIN - CALL available_clean; - CALL visible_clean; +BEGIN + CALL available_clean; + CALL visible_clean; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6916,13 +6916,13 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - - DECLARE vDateShort DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); - - DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; +BEGIN + + DECLARE vDateShort DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); + + DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8386,158 +8386,158 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT) -BEGIN - DECLARE vRef INT; - DECLARE vBuy INT; - DECLARE vItem INT; - DECLARE vQty INT; - DECLARE vPackage INT; - DECLARE vIsLot BOOLEAN; - DECLARE vForceToPacking INT DEFAULT 2; - - -- Carga los datos necesarios del EKT - - SELECT ref, qty, package INTO vRef, vQty, vPackage - FROM ekt e - LEFT JOIN item i ON e.ref = i.id - WHERE e.id = vSelf; - - -- Inserta el cubo si no existe - - IF vPackage = 800 - THEN - SET vPackage = 800 + vQty; - - INSERT IGNORE INTO vn2008.Cubos SET - Id_Cubo = vPackage, - x = 7200 / vQty, - y = 1; - ELSE - INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) - SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) - FROM bucket WHERE bucket_id = vPackage; - - IF ROW_COUNT() > 0 - THEN - INSERT INTO vn2008.mail SET - `subject` = 'Cubo añadido', - `text` = CONCAT('Se ha añadido el cubo: ', vPackage), - `to` = 'ekt@verdnatura.es'; - END IF; - END IF; - - -- Intenta obtener el artículo en base a los atributos holandeses - - INSERT IGNORE INTO item_track SET - item_id = vRef; - - SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem - FROM vn2008.buy_edi e - JOIN item_track t ON t.item_id = e.ref - LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref - LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id - JOIN vn2008.config cfg - WHERE e.id = vSelf - AND l.id != vSelf - AND c.Id_Article != cfg.generic_item - AND IF(t.s1, l.s1 = e.s1, TRUE) - AND IF(t.s2, l.s2 = e.s2, TRUE) - AND IF(t.s3, l.s3 = e.s3, TRUE) - AND IF(t.s4, l.s4 = e.s4, TRUE) - AND IF(t.s5, l.s5 = e.s5, TRUE) - AND IF(t.s6, l.s6 = e.s6, TRUE) - AND IF(t.kop, l.kop = e.kop, TRUE) - AND IF(t.pac, l.pac = e.pac, TRUE) - AND IF(t.cat, l.cat = e.cat, TRUE) - AND IF(t.ori, l.ori = e.ori, TRUE) - AND IF(t.pro, l.pro = e.pro, TRUE) - AND IF(t.sub, l.sub = e.sub, TRUE) - AND IF(t.package, l.package = e.package, TRUE) - AND c.Id_Article < 170000 - ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; - - -- Determina si el articulo se vende por lotes - - IF vItem - THEN - SELECT COUNT(*) > 0 INTO vIsLot - FROM vn2008.Articles a - LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - WHERE a.Id_Article = vItem - AND t.`transaction`; - - -- Si el articulo se vende por lotes se inserta un nuevo artículo - - IF vIsLot - THEN - INSERT INTO vn2008.Articles ( - Article - ,Medida - ,Categoria - ,Id_Origen - ,iva_group_id - ,Foto - ,Color - ,Codintrastat - ,tipo_id - ,Tallos - ) - SELECT - i.`name` - ,IFNULL(e.s1, e.pac) - ,e.cat - ,IFNULL(o.id, 17) - ,IFNULL(a.iva_group_id, 1) - ,a.Foto - ,a.Color - ,a.Codintrastat - ,IFNULL(a.tipo_id, 10) - ,IF(a.tipo_id = 15, 0, 1) - FROM vn2008.buy_edi e - LEFT JOIN item i ON i.id = e.ref - LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori - LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem - WHERE e.id = vSelf; - - SET vItem = LAST_INSERT_ID(); - END IF; - END IF; - - -- Inserta la compra asociada al EKT - - INSERT INTO vn2008.Compres - ( - Id_Entrada - ,buy_edi_id - ,Costefijo - ,Id_Article - ,`grouping` - ,caja - ,Packing - ,Cantidad - ,Productor - ,Etiquetas - ,Id_Cubo - ) - SELECT - cfg.edi_entry - ,vSelf - ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri - ,IFNULL(vItem, cfg.generic_item) - ,IFNULL(c.`grouping`, e.pac) - ,vForceToPacking - ,@pac := e.pac / @t - ,@pac * e.qty - ,s.company_name - ,e.qty - ,IFNULL(c.Id_Cubo, e.package) - FROM vn2008.buy_edi e - LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy - LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article - LEFT JOIN supplier s ON e.pro = s.supplier_id - JOIN vn2008.config cfg - WHERE e.id = vSelf - LIMIT 1; +BEGIN + DECLARE vRef INT; + DECLARE vBuy INT; + DECLARE vItem INT; + DECLARE vQty INT; + DECLARE vPackage INT; + DECLARE vIsLot BOOLEAN; + DECLARE vForceToPacking INT DEFAULT 2; + + -- Carga los datos necesarios del EKT + + SELECT ref, qty, package INTO vRef, vQty, vPackage + FROM ekt e + LEFT JOIN item i ON e.ref = i.id + WHERE e.id = vSelf; + + -- Inserta el cubo si no existe + + IF vPackage = 800 + THEN + SET vPackage = 800 + vQty; + + INSERT IGNORE INTO vn2008.Cubos SET + Id_Cubo = vPackage, + x = 7200 / vQty, + y = 1; + ELSE + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) + SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) + FROM bucket WHERE bucket_id = vPackage; + + IF ROW_COUNT() > 0 + THEN + INSERT INTO vn2008.mail SET + `subject` = 'Cubo añadido', + `text` = CONCAT('Se ha añadido el cubo: ', vPackage), + `to` = 'ekt@verdnatura.es'; + END IF; + END IF; + + -- Intenta obtener el artículo en base a los atributos holandeses + + INSERT IGNORE INTO item_track SET + item_id = vRef; + + SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem + FROM vn2008.buy_edi e + JOIN item_track t ON t.item_id = e.ref + LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref + LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id + JOIN vn2008.config cfg + WHERE e.id = vSelf + AND l.id != vSelf + AND c.Id_Article != cfg.generic_item + AND IF(t.s1, l.s1 = e.s1, TRUE) + AND IF(t.s2, l.s2 = e.s2, TRUE) + AND IF(t.s3, l.s3 = e.s3, TRUE) + AND IF(t.s4, l.s4 = e.s4, TRUE) + AND IF(t.s5, l.s5 = e.s5, TRUE) + AND IF(t.s6, l.s6 = e.s6, TRUE) + AND IF(t.kop, l.kop = e.kop, TRUE) + AND IF(t.pac, l.pac = e.pac, TRUE) + AND IF(t.cat, l.cat = e.cat, TRUE) + AND IF(t.ori, l.ori = e.ori, TRUE) + AND IF(t.pro, l.pro = e.pro, TRUE) + AND IF(t.sub, l.sub = e.sub, TRUE) + AND IF(t.package, l.package = e.package, TRUE) + AND c.Id_Article < 170000 + ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; + + -- Determina si el articulo se vende por lotes + + IF vItem + THEN + SELECT COUNT(*) > 0 INTO vIsLot + FROM vn2008.Articles a + LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id + WHERE a.Id_Article = vItem + AND t.`transaction`; + + -- Si el articulo se vende por lotes se inserta un nuevo artículo + + IF vIsLot + THEN + INSERT INTO vn2008.Articles ( + Article + ,Medida + ,Categoria + ,Id_Origen + ,iva_group_id + ,Foto + ,Color + ,Codintrastat + ,tipo_id + ,Tallos + ) + SELECT + i.`name` + ,IFNULL(e.s1, e.pac) + ,e.cat + ,IFNULL(o.id, 17) + ,IFNULL(a.iva_group_id, 1) + ,a.Foto + ,a.Color + ,a.Codintrastat + ,IFNULL(a.tipo_id, 10) + ,IF(a.tipo_id = 15, 0, 1) + FROM vn2008.buy_edi e + LEFT JOIN item i ON i.id = e.ref + LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori + LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem + WHERE e.id = vSelf; + + SET vItem = LAST_INSERT_ID(); + END IF; + END IF; + + -- Inserta la compra asociada al EKT + + INSERT INTO vn2008.Compres + ( + Id_Entrada + ,buy_edi_id + ,Costefijo + ,Id_Article + ,`grouping` + ,caja + ,Packing + ,Cantidad + ,Productor + ,Etiquetas + ,Id_Cubo + ) + SELECT + cfg.edi_entry + ,vSelf + ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri + ,IFNULL(vItem, cfg.generic_item) + ,IFNULL(c.`grouping`, e.pac) + ,vForceToPacking + ,@pac := e.pac / @t + ,@pac * e.qty + ,s.company_name + ,e.qty + ,IFNULL(c.Id_Cubo, e.package) + FROM vn2008.buy_edi e + LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy + LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article + LEFT JOIN supplier s ON e.pro = s.supplier_id + JOIN vn2008.config cfg + WHERE e.id = vSelf + LIMIT 1; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8587,154 +8587,154 @@ CREATE DEFINER=`root`@`%` PROCEDURE `exchange_new`( IN `vAuction` SMALLINT, IN `vPackage` INT, IN `vPutOrderFk` INT) -BEGIN +BEGIN /** * Adds a new exchange, generates it's barcode and * inserts/updates the transaction. When the referenced * transaction exists as provisional, updates it with - * the new values. - */ - DECLARE vEkt INT; - DECLARE vRewriteKop INT DEFAULT NULL; - DECLARE vBarcode CHAR(15) DEFAULT NULL; - DECLARE vIsDuplicated BOOL; + * the new values. + */ + DECLARE vEkt INT; + DECLARE vRewriteKop INT DEFAULT NULL; + DECLARE vBarcode CHAR(15) DEFAULT NULL; + DECLARE vIsDuplicated BOOL; DECLARE vUpdateExistent BOOL DEFAULT FALSE; - DECLARE duplicateKey CONDITION FOR 1062; - - DECLARE CONTINUE HANDLER FOR duplicateKey - SET vIsDuplicated = TRUE; - - -- Generates the barcode - - IF vAgj != 0 AND vAgj IS NOT NULL - THEN - SET vBarcode = CONCAT( - LPAD(vAuction, 2, 0), - LPAD(IFNULL(vClock, 99), 2, 0), - LPAD(DAYOFYEAR(vDate), 3, 0), - IF(vClock IS NULL OR vClock = 99, - LPAD(vAgj, 7, 0), - CONCAT(LPAD(vAgj, 5, 0), '01') - ), - '0' - ); - END IF; - - -- Rewrites the kop parameter - - IF vKop IS NULL THEN - SELECT defaultKop INTO vKop FROM exchangeConfig; - END IF; - - SELECT e.kop INTO vRewriteKop - FROM mailSender e - JOIN mail m ON m.senderFk = e.id - WHERE m.id = vMailFk; - - SET vKop = IFNULL(vRewriteKop, vKop); - - -- Inserts the new transaction + DECLARE duplicateKey CONDITION FOR 1062; - SET vIsDuplicated = FALSE; - INSERT INTO ekt SET - barcode = IFNULL(vBarcode, barcode) - ,deliveryNumber = vDeliveryNumber - ,entryYear = YEAR(vDate) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk; - - -- If it exists duplicado updates it - - IF NOT vIsDuplicated - THEN - SET vEkt = LAST_INSERT_ID(); - CALL ekt_load (vEkt); - - ELSEIF vDeliveryNumber != 0 - AND vDeliveryNumber IS NOT NULL - THEN - SELECT id INTO vEkt - FROM ekt - WHERE deliveryNumber = vDeliveryNumber; - - SELECT COUNT(*) = 0 INTO vUpdateExistent - FROM ekt t - JOIN `exchange` b ON b.ektFk = t.id - JOIN exchangeConfig c - WHERE t.deliveryNumber = vDeliveryNumber - AND t.entryYear = YEAR(vDate) - AND b.typeFk != c.presaleFk; - END IF; - - IF vUpdateExistent - THEN - UPDATE ekt SET - barcode = IFNULL(vBarcode, barcode) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk - WHERE id = vEkt; - END IF; - - -- Registers the exchange - - INSERT INTO `exchange` SET - mailFk = vMailFk - ,typeFk = vType - ,ektFk = vEkt; + DECLARE CONTINUE HANDLER FOR duplicateKey + SET vIsDuplicated = TRUE; + + -- Generates the barcode + + IF vAgj != 0 AND vAgj IS NOT NULL + THEN + SET vBarcode = CONCAT( + LPAD(vAuction, 2, 0), + LPAD(IFNULL(vClock, 99), 2, 0), + LPAD(DAYOFYEAR(vDate), 3, 0), + IF(vClock IS NULL OR vClock = 99, + LPAD(vAgj, 7, 0), + CONCAT(LPAD(vAgj, 5, 0), '01') + ), + '0' + ); + END IF; + + -- Rewrites the kop parameter + + IF vKop IS NULL THEN + SELECT defaultKop INTO vKop FROM exchangeConfig; + END IF; + + SELECT e.kop INTO vRewriteKop + FROM mailSender e + JOIN mail m ON m.senderFk = e.id + WHERE m.id = vMailFk; + + SET vKop = IFNULL(vRewriteKop, vKop); + + -- Inserts the new transaction + + SET vIsDuplicated = FALSE; + INSERT INTO ekt SET + barcode = IFNULL(vBarcode, barcode) + ,deliveryNumber = vDeliveryNumber + ,entryYear = YEAR(vDate) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk; + + -- If it exists duplicado updates it + + IF NOT vIsDuplicated + THEN + SET vEkt = LAST_INSERT_ID(); + CALL ekt_load (vEkt); + + ELSEIF vDeliveryNumber != 0 + AND vDeliveryNumber IS NOT NULL + THEN + SELECT id INTO vEkt + FROM ekt + WHERE deliveryNumber = vDeliveryNumber; + + SELECT COUNT(*) = 0 INTO vUpdateExistent + FROM ekt t + JOIN `exchange` b ON b.ektFk = t.id + JOIN exchangeConfig c + WHERE t.deliveryNumber = vDeliveryNumber + AND t.entryYear = YEAR(vDate) + AND b.typeFk != c.presaleFk; + END IF; + + IF vUpdateExistent + THEN + UPDATE ekt SET + barcode = IFNULL(vBarcode, barcode) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk + WHERE id = vEkt; + END IF; + + -- Registers the exchange + + INSERT INTO `exchange` SET + mailFk = vMailFk + ,typeFk = vType + ,ektFk = vEkt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10810,30 +10810,30 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `item_listAllocation`(IN `vWh` TINYINT, IN `vDate` DATE, IN `vType` INT, IN `vPrefix` VARCHAR(255), IN `vUseIds` BOOLEAN) -BEGIN -/** - * Lists visible items and it's box sizes of the specified - * type at specified date. - * - * @param vWh The warehouse id - * @param vDate The visible date - * @param vType The type id - * @param vPrefix The article prefix to filter or %NULL for all - * @param vUseIds Whether to order the result by item id - * @select List of visible items with it's box sizes - */ - CALL item_getVisible(vWh, vDate, vType, vPrefix); - - IF vUseIds - THEN - SELECT * FROM tmp.itemVisible - ORDER BY Id_Article; - ELSE - SELECT * FROM tmp.itemVisible - ORDER BY Article, packing; - END IF; - - DROP TEMPORARY TABLE tmp.itemVisible; +BEGIN +/** + * Lists visible items and it's box sizes of the specified + * type at specified date. + * + * @param vWh The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @param vUseIds Whether to order the result by item id + * @select List of visible items with it's box sizes + */ + CALL item_getVisible(vWh, vDate, vType, vPrefix); + + IF vUseIds + THEN + SELECT * FROM tmp.itemVisible + ORDER BY Id_Article; + ELSE + SELECT * FROM tmp.itemVisible + ORDER BY Article, packing; + END IF; + + DROP TEMPORARY TABLE tmp.itemVisible; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -16189,8 +16189,8 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `log_add_beta`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) -proc: BEGIN - -- XXX: Disabled while testing +proc: BEGIN + -- XXX: Disabled while testing DECLARE vLanded DATE; DECLARE vWarehouseFk INT; DECLARE vBuyerFk INT; @@ -16198,20 +16198,20 @@ proc: BEGIN DECLARE vItemFk INT; DECLARE vItemName VARCHAR(50); - -- LEAVE proc; + -- LEAVE proc; - IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vOldId, - operation = 'delete'; - END IF; - - IF vNewId IS NOT NULL THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vNewId, - operation = 'insert'; + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vOldId, + operation = 'delete'; + END IF; + + IF vNewId IS NOT NULL THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vNewId, + operation = 'insert'; END IF; IF vTableName = 'buy' THEN @@ -16241,7 +16241,7 @@ proc: BEGIN END IF; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -16509,29 +16509,29 @@ CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshSale`( BEGIN DROP TEMPORARY TABLE IF EXISTS tValues; CREATE TEMPORARY TABLE tValues - ENGINE = MEMORY - SELECT - m.id saleFk, - m.ticketFk, - m.itemFk, - t.warehouseFk, - t.shipped, + ENGINE = MEMORY + SELECT + m.id saleFk, + m.ticketFk, + m.itemFk, + t.warehouseFk, + t.shipped, ABS(m.quantity) quantity, m.created, TIMESTAMPADD(DAY, tp.life, t.shipped) expired, m.quantity < 0 isIn, - m.isPicked OR s.alertLevel > 1 isPicked - FROM vn.sale m - JOIN vn.ticket t ON t.id = m.ticketFk + m.isPicked OR s.alertLevel > 1 isPicked + FROM vn.sale m + JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id JOIN vn.item i ON i.id = m.itemFk - JOIN vn.itemType tp ON tp.id = i.typeFk + JOIN vn.itemType tp ON tp.id = i.typeFk WHERE ( - vTableId IS NULL - OR (vTableName = 'ticket' AND t.id = vTableId) - OR (vTableName = 'sale' AND m.id = vTableId) - ) - AND t.shipped >= vn.getInventoryDate() + vTableId IS NULL + OR (vTableName = 'ticket' AND t.id = vTableId) + OR (vTableName = 'sale' AND m.id = vTableId) + ) + AND t.shipped >= vn.getInventoryDate() AND m.quantity != 0; REPLACE INTO inbound ( @@ -16564,7 +16564,7 @@ BEGIN FROM tValues WHERE !isIn; - DROP TEMPORARY TABLE tValues; + DROP TEMPORARY TABLE tValues; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29495,90 +29495,90 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN - - DECLARE vCurrentCount INT; - DECLARE vCheckSum INT; - DECLARE vIsAlreadyNotified BOOLEAN; - DECLARE vTableQueue TEXT; - DECLARE vLineQueue TEXT; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vCur CURSOR FOR - SELECT CONCAT(' - ', IFNULL(pq.id, ''), ' - ', IFNULL(p.path, ''),' - ', IFNULL(i.Informe, ''),' - ', IFNULL(e.Estado, ''),' - ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' - ', IFNULL(pq.`error`, ''),' - ') - FROM vn.printingQueue pq - LEFT JOIN vn.worker w ON w.id = pq.worker - LEFT JOIN vn.printer p ON p.id = pq.printer - LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report - JOIN vn2008.Estados e ON e.Id_Estado = pq.state - LIMIT 30; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum - FROM vn.printingQueue WHERE state = 1; - - SELECT isAlreadyNotified INTO vIsAlreadyNotified - FROM printingQueueCheck; - - IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND - (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND - vIsAlreadyNotified = FALSE AND vCurrentCount > 0 - THEN - - SELECT ' - - - - - - - - ' INTO vTableQueue; - - OPEN vCur; - - l: LOOP - - SET vDone = FALSE; - - FETCH vCur INTO vLineQueue; - - IF vDone THEN - LEAVE l; - END IF; - - SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; - - END LOOP; - - CLOSE vCur; - - INSERT INTO vn2008.mail (`to`, subject, text) - VALUES ('cau@verdnatura.es, sysadmin@verdnatura.es', - 'servidor de impresion parado', - CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); - - UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; - END IF; - - IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND - vIsAlreadyNotified = TRUE - THEN - UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; - END IF; - - UPDATE printingQueueCheck - SET lastCount = vCurrentCount, - lastCheckSum = vCheckSum; - +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN + + DECLARE vCurrentCount INT; + DECLARE vCheckSum INT; + DECLARE vIsAlreadyNotified BOOLEAN; + DECLARE vTableQueue TEXT; + DECLARE vLineQueue TEXT; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCur CURSOR FOR + SELECT CONCAT(' + ', IFNULL(pq.id, ''), ' + ', IFNULL(p.path, ''),' + ', IFNULL(i.Informe, ''),' + ', IFNULL(e.Estado, ''),' + ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' + ', IFNULL(pq.`error`, ''),' + ') + FROM vn.printingQueue pq + LEFT JOIN vn.worker w ON w.id = pq.worker + LEFT JOIN vn.printer p ON p.id = pq.printer + LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report + JOIN vn2008.Estados e ON e.Id_Estado = pq.state + LIMIT 30; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum + FROM vn.printingQueue WHERE state = 1; + + SELECT isAlreadyNotified INTO vIsAlreadyNotified + FROM printingQueueCheck; + + IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND + (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND + vIsAlreadyNotified = FALSE AND vCurrentCount > 0 + THEN + + SELECT ' + + + + + + + + ' INTO vTableQueue; + + OPEN vCur; + + l: LOOP + + SET vDone = FALSE; + + FETCH vCur INTO vLineQueue; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; + + END LOOP; + + CLOSE vCur; + + INSERT INTO vn2008.mail (`to`, subject, text) + VALUES ('cau@verdnatura.es, sysadmin@verdnatura.es', + 'servidor de impresion parado', + CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); + + UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; + END IF; + + IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND + vIsAlreadyNotified = TRUE + THEN + UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; + END IF; + + UPDATE printingQueueCheck + SET lastCount = vCurrentCount, + lastCheckSum = vCheckSum; + END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -35117,27 +35117,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean__`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE oneYearAgo DATE; - DECLARE twoYearsAgo DATE; - DECLARE fourYearsAgo DATE; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); - SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); - SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); - - DELETE FROM vn.message WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; - DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; - DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); - CALL shelving_clean; - +BEGIN + DECLARE vDateShort DATETIME; + DECLARE oneYearAgo DATE; + DECLARE twoYearsAgo DATE; + DECLARE fourYearsAgo DATE; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); + SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); + SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); + + DELETE FROM vn.message WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; + DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; + DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); + CALL shelving_clean; + CALL vn.ticketPackagingRecovery; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35980,54 +35980,54 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker__`() -BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vClientFk INT; - - DECLARE rs CURSOR FOR - SELECT c.clientFk - FROM tmp.clientGetDebt c - LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk - WHERE IFNULL(r.risk,0) = 0; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - SELECT cd.id as clientFk - FROM bs.clientDied cd - LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id - JOIN vn.client c ON c.id = cd.id - JOIN vn.province p ON p.id = c.provinceFk - JOIN vn.country co ON co.id = p.countryFk - WHERE cd.Aviso = 'TERCER AVISO' - AND cp.clientFk IS NULL - AND co.country NOT IN ('Portugal','Francia','España exento') - AND c.salesPersonFk IS NOT NULL; - - CALL vn.clientGetDebt(curdate()); - - DROP TEMPORARY TABLE IF EXISTS tmp.contador; - CREATE TEMPORARY TABLE tmp.contador (id INT) - ENGINE = MEMORY; - - OPEN rs; - FETCH rs INTO vClientFk; - - WHILE NOT done DO - INSERT INTO tmp.contador SET id = vClientFk; - CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vClientFk INT; + + DECLARE rs CURSOR FOR + SELECT c.clientFk + FROM tmp.clientGetDebt c + LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk + WHERE IFNULL(r.risk,0) = 0; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT cd.id as clientFk + FROM bs.clientDied cd + LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id + JOIN vn.client c ON c.id = cd.id + JOIN vn.province p ON p.id = c.provinceFk + JOIN vn.country co ON co.id = p.countryFk + WHERE cd.Aviso = 'TERCER AVISO' + AND cp.clientFk IS NULL + AND co.country NOT IN ('Portugal','Francia','España exento') + AND c.salesPersonFk IS NOT NULL; + + CALL vn.clientGetDebt(curdate()); + + DROP TEMPORARY TABLE IF EXISTS tmp.contador; + CREATE TEMPORARY TABLE tmp.contador (id INT) + ENGINE = MEMORY; + + OPEN rs; + FETCH rs INTO vClientFk; + + WHILE NOT done DO + INSERT INTO tmp.contador SET id = vClientFk; + CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; INSERT INTO vn.clientLog (originFk, userFk, `action`, description) VALUES (vClientFk, account.userGetId(), 'update', CONCAT('Se ha desasignado el cliente por que no ha comprado en 3 meses')); - + REPLACE bs.clientNewBorn(clientFk, shipped) - VALUES(vClientFk, CURDATE()); - FETCH rs INTO vClientFk; - END WHILE; - - CLOSE rs; + VALUES(vClientFk, CURDATE()); + FETCH rs INTO vClientFk; + END WHILE; + + CLOSE rs; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -38951,216 +38951,216 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryConverter`(IN `vEntry` INT) -BEGIN - - DECLARE vWarehouseIn INT; - DECLARE vWarehouseOut INT; - DECLARE vTravel INT; - - DECLARE done BOOL DEFAULT FALSE; - - DECLARE vId_Entrada INT; - DECLARE vId_Article INT; - DECLARE vEtiquetas INT; - DECLARE vId_Cubo VARCHAR(10); - DECLARE vPacking INT; - DECLARE vGrouping INT; - DECLARE vCantidad INT; - DECLARE vCostefijo DECIMAL(10,3); - DECLARE vPortefijo DECIMAL(10,3); - DECLARE vEmbalajefijo DECIMAL(10); - DECLARE vComisionfija DECIMAL(10,3); - DECLARE vCaja INT; - DECLARE vNicho VARCHAR(5); - DECLARE vTarifa1 DECIMAL(10,2); - DECLARE vTarifa2 DECIMAL(10,2); - DECLARE vTarifa3 DECIMAL(10,2); - DECLARE vPVP DECIMAL(10,2); - DECLARE vCompra INT; - - DECLARE rs CURSOR FOR - SELECT - b.Id_Entrada, - b.Id_Article, - b.Etiquetas, - b.Id_Cubo, - b.Packing, - b.`grouping`, - b.Cantidad, - b.Costefijo, - b.Portefijo, - b.Embalajefijo, - b.Comisionfija, - b.caja, - b.Nicho, - b.Tarifa1, - b.Tarifa2, - b.Tarifa3, - b.PVP - FROM vn2008.Compres b - JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article - WHERE Id_Entrada = vEntry; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT warehouseInFk, warehouseOutFk, tr.id - INTO vWarehouseIn, vWarehouseOut, vTravel - FROM travel tr - JOIN entry e ON e.travelFk = tr.id - WHERE e.id = vEntry; - - UPDATE travel - SET warehouseInFk = vWarehouseOut, - warehouseOutFk = vWarehouseIn - WHERE id = vTravel; - - UPDATE vn2008.Compres c - LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article - SET Etiquetas = 0, Cantidad = 0 - WHERE c.Id_Entrada = vEntry - AND ic.espItemFk IS NULL; - - OPEN rs; - - DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - WHILE NOT done DO - - -- Primero la linea original con las cantidades invertidas - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - VALUES - ( - vId_Entrada, - vId_Article, - - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP); - - -- Ahora la linea nueva, con el item genérico - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - SELECT - vId_Entrada, - genItemFk as Id_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP - FROM itemConversor - WHERE espItemFk = vId_Article; - - SELECT LAST_INSERT_ID() - INTO vCompra; - - REPLACE vn2008.Compres_mark(Id_Compra,`comment`) - SELECT vCompra, vId_Article; - - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - END WHILE; - - - CLOSE rs; - - - +BEGIN + + DECLARE vWarehouseIn INT; + DECLARE vWarehouseOut INT; + DECLARE vTravel INT; + + DECLARE done BOOL DEFAULT FALSE; + + DECLARE vId_Entrada INT; + DECLARE vId_Article INT; + DECLARE vEtiquetas INT; + DECLARE vId_Cubo VARCHAR(10); + DECLARE vPacking INT; + DECLARE vGrouping INT; + DECLARE vCantidad INT; + DECLARE vCostefijo DECIMAL(10,3); + DECLARE vPortefijo DECIMAL(10,3); + DECLARE vEmbalajefijo DECIMAL(10); + DECLARE vComisionfija DECIMAL(10,3); + DECLARE vCaja INT; + DECLARE vNicho VARCHAR(5); + DECLARE vTarifa1 DECIMAL(10,2); + DECLARE vTarifa2 DECIMAL(10,2); + DECLARE vTarifa3 DECIMAL(10,2); + DECLARE vPVP DECIMAL(10,2); + DECLARE vCompra INT; + + DECLARE rs CURSOR FOR + SELECT + b.Id_Entrada, + b.Id_Article, + b.Etiquetas, + b.Id_Cubo, + b.Packing, + b.`grouping`, + b.Cantidad, + b.Costefijo, + b.Portefijo, + b.Embalajefijo, + b.Comisionfija, + b.caja, + b.Nicho, + b.Tarifa1, + b.Tarifa2, + b.Tarifa3, + b.PVP + FROM vn2008.Compres b + JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article + WHERE Id_Entrada = vEntry; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SELECT warehouseInFk, warehouseOutFk, tr.id + INTO vWarehouseIn, vWarehouseOut, vTravel + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + WHERE e.id = vEntry; + + UPDATE travel + SET warehouseInFk = vWarehouseOut, + warehouseOutFk = vWarehouseIn + WHERE id = vTravel; + + UPDATE vn2008.Compres c + LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article + SET Etiquetas = 0, Cantidad = 0 + WHERE c.Id_Entrada = vEntry + AND ic.espItemFk IS NULL; + + OPEN rs; + + DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + WHILE NOT done DO + + -- Primero la linea original con las cantidades invertidas + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + VALUES + ( + vId_Entrada, + vId_Article, + - vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + - vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP); + + -- Ahora la linea nueva, con el item genérico + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + SELECT + vId_Entrada, + genItemFk as Id_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP + FROM itemConversor + WHERE espItemFk = vId_Article; + + SELECT LAST_INSERT_ID() + INTO vCompra; + + REPLACE vn2008.Compres_mark(Id_Compra,`comment`) + SELECT vCompra, vId_Article; + + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + END WHILE; + + + CLOSE rs; + + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39222,62 +39222,62 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryPrepare`(IN `idE` BIGINT) -BEGIN - SELECT - b.quantity / b.packing AS Paquetes, - b.packing AS `Grouping`, - barcode, - 'ASEGURADO' AS asegurado, - ic.name, - ic.order, - s.name AS Consignatario, - e.supplierFk AS Id_Cliente, - e.isOrdered, - e.isConfirmed, - 10 AS Calidad, - LPAD(IFNULL(cpd.id, ip.code), - 5, - '0') AS path, - b.entryFk AS Id_Ticket, - t.landed AS Fecha, - b.itemFk, - b.quantity, - i.name AS Concepte, - i.size, - i.inkFk, - i.category, - o.code AS Origen, - 0 AS Bultos, - wIn.`name` AS Tipo, - 0 AS OK, - 0 AS Reservado, - i.stems, - b.id AS Id_Movimiento, - ip.code, - 'PEDIDO ASEGURADO' AS MSG, - 0 AS Seguro, - i.image, - pr.name AS producer - FROM vn.buy b - JOIN vn.entry e ON b.entryFk = e.id - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk - JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk - JOIN vn.item i ON i.id = b.itemFk - JOIN vn.itemType it ON it.id =i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.packaging pkg ON pkg.id = b.packageFk - LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk - LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk - LEFT JOIN vn.origin o ON o.id = i.originFk - LEFT JOIN vn.supplier s ON s.id = e.supplierFk - LEFT JOIN vn.producer pr on pr.id = i.producerFk - LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway - WHERE - NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid - AND e.id = 158772 - AND i.typeFk IS NOT NULL - AND ic.merchandise IS NOT FALSE; +BEGIN + SELECT + b.quantity / b.packing AS Paquetes, + b.packing AS `Grouping`, + barcode, + 'ASEGURADO' AS asegurado, + ic.name, + ic.order, + s.name AS Consignatario, + e.supplierFk AS Id_Cliente, + e.isOrdered, + e.isConfirmed, + 10 AS Calidad, + LPAD(IFNULL(cpd.id, ip.code), + 5, + '0') AS path, + b.entryFk AS Id_Ticket, + t.landed AS Fecha, + b.itemFk, + b.quantity, + i.name AS Concepte, + i.size, + i.inkFk, + i.category, + o.code AS Origen, + 0 AS Bultos, + wIn.`name` AS Tipo, + 0 AS OK, + 0 AS Reservado, + i.stems, + b.id AS Id_Movimiento, + ip.code, + 'PEDIDO ASEGURADO' AS MSG, + 0 AS Seguro, + i.image, + pr.name AS producer + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk + JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id =i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.packaging pkg ON pkg.id = b.packageFk + LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk + LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN vn.supplier s ON s.id = e.supplierFk + LEFT JOIN vn.producer pr on pr.id = i.producerFk + LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway + WHERE + NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid + AND e.id = 158772 + AND i.typeFk IS NOT NULL + AND ic.merchandise IS NOT FALSE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43012,38 +43012,38 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemLastEntries`(IN `vItem` INT, IN `vDays` DATE) -BEGIN - SELECT - w.id AS warehouseFk, - w.name AS warehouse, - tr.landed, - b.entryFk, - b.isIgnored, - b.price2, - b.price3, - b.stickers, - b.packing, - b.`grouping`, - b.groupingMode, - i.stems, - b.quantity, - b.buyingValue, - b.packageFk , - s.id AS supplierFk, - s.name AS supplier - FROM itemType it - RIGHT JOIN (entry e - LEFT JOIN supplier s ON s.id = e.supplierFk - RIGHT JOIN buy b ON b.entryFk = e.id - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk - LEFT JOIN travel tr ON tr.id = e.travelFk - LEFT JOIN warehouse w ON w.id = tr.warehouseInFk - LEFT JOIN origin o ON o.id = i.originFk - ) ON it.id = i.typeFk - LEFT JOIN edi.ekt ek ON b.ektFk = ek.id - WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND DATE_ADD(CURDATE(), INTERVAl + 10 DAY) - ORDER BY tr.landed DESC , b.id DESC; +BEGIN + SELECT + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.`grouping`, + b.groupingMode, + i.stems, + b.quantity, + b.buyingValue, + b.packageFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND DATE_ADD(CURDATE(), INTERVAl + 10 DAY) + ORDER BY tr.landed DESC , b.id DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47362,77 +47362,77 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake`(IN `vTicketFk` INT, IN `vSectorFk` INT) -BEGIN - - SET @rest:= CAST(0 AS DECIMAL(10,0)); - SET @saleFk := CAST(0 AS DECIMAL(10,0)); - SET @reserved := CAST(0 AS DECIMAL(10,0)); - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN sale s ON s.id = sis.saleFk - SET ish.visible = sis.quantity + ish.visible, - ish.available = sis.quantity + ish.visible - WHERE s.ticketFk = vTicketFk; - - DELETE sis.* - FROM saleItemShelving sis - JOIN sale s ON s.id = sis.saleFk - WHERE s.ticketFk = vTicketFk; - - INSERT INTO saleItemShelving( saleFk, - itemShelvingFk, - quantity, - ubication) - SELECT saleFk, - itemShelvingFk, - CAST(Reserved as DECIMAL(10,0)) as Reserved, - ubication - FROM - (SELECT saleFk, - itemShelvingFk, - ubication, - @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, - @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, - @rest := @rest - @reserved, - @saleFk := saleFk - FROM - ( SELECT s.id as saleFk, - ish.created, - ish.id as itemShelvingFk, - ish.available, - s.quantity, - ish.packing, - CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk - JOIN vn.parking p ON p.sectorFk = sc.id - JOIN vn.shelving sh ON sh.parkingFk = p.id - JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk - WHERE t.id = vTicketFk - AND sc.id = vSectorFk - AND s.quantity MOD ish.packing = 0 - AND s.quantity >= ish.packing - ORDER BY s.id, - sh.priority DESC, - ish.packing DESC, - ish.created - ) sub - ) sub2 - WHERE Reserved > 0; - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN vn.sale s ON s.id = sis.saleFk - SET ish.available = ish.visible - sis.quantity, - ish.visible = ish.visible - sis.quantity - WHERE s.ticketFk = vTicketFk - AND s.isPicked = FALSE; - - CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); - - +BEGIN + + SET @rest:= CAST(0 AS DECIMAL(10,0)); + SET @saleFk := CAST(0 AS DECIMAL(10,0)); + SET @reserved := CAST(0 AS DECIMAL(10,0)); + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN sale s ON s.id = sis.saleFk + SET ish.visible = sis.quantity + ish.visible, + ish.available = sis.quantity + ish.visible + WHERE s.ticketFk = vTicketFk; + + DELETE sis.* + FROM saleItemShelving sis + JOIN sale s ON s.id = sis.saleFk + WHERE s.ticketFk = vTicketFk; + + INSERT INTO saleItemShelving( saleFk, + itemShelvingFk, + quantity, + ubication) + SELECT saleFk, + itemShelvingFk, + CAST(Reserved as DECIMAL(10,0)) as Reserved, + ubication + FROM + (SELECT saleFk, + itemShelvingFk, + ubication, + @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, + @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, + @rest := @rest - @reserved, + @saleFk := saleFk + FROM + ( SELECT s.id as saleFk, + ish.created, + ish.id as itemShelvingFk, + ish.available, + s.quantity, + ish.packing, + CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk + JOIN vn.parking p ON p.sectorFk = sc.id + JOIN vn.shelving sh ON sh.parkingFk = p.id + JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk + WHERE t.id = vTicketFk + AND sc.id = vSectorFk + AND s.quantity MOD ish.packing = 0 + AND s.quantity >= ish.packing + ORDER BY s.id, + sh.priority DESC, + ish.packing DESC, + ish.created + ) sub + ) sub2 + WHERE Reserved > 0; + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN vn.sale s ON s.id = sis.saleFk + SET ish.available = ish.visible - sis.quantity, + ish.visible = ish.visible - sis.quantity + WHERE s.ticketFk = vTicketFk + AND s.isPicked = FALSE; + + CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47925,33 +47925,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `scanTreeCreate`() -BEGIN - CALL nestTree( - 'vn2008', - 'scan', - 'vn2008', - 'scanTree' - ); - - UPDATE vn2008.scanTree st - JOIN ( - SELECT sl.scan_id, - MAX(sl.odbc_date) lastScanned, - COUNT(DISTINCT t.routeFk) routeCount, - MIN(t.routeFk) mod 1000 as minRoute, - MAX(t.routeFk) mod 1000 as maxRoute, - COUNT(sl.scan_line_id) as scanned - FROM vn2008.scan_line sl - JOIN expedition e ON e.id = sl.`code` - JOIN ticket t ON t.id = e.ticketFk - WHERE t.routeFk - GROUP BY sl.scan_id - ) rs ON rs.scan_id = st.id - SET st.lastScanned = rs.lastScanned, - st.routeCount = rs.routeCount, - st.minRoute = rs.minRoute, - st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), - st.scanned = rs.scanned; +BEGIN + CALL nestTree( + 'vn2008', + 'scan', + 'vn2008', + 'scanTree' + ); + + UPDATE vn2008.scanTree st + JOIN ( + SELECT sl.scan_id, + MAX(sl.odbc_date) lastScanned, + COUNT(DISTINCT t.routeFk) routeCount, + MIN(t.routeFk) mod 1000 as minRoute, + MAX(t.routeFk) mod 1000 as maxRoute, + COUNT(sl.scan_line_id) as scanned + FROM vn2008.scan_line sl + JOIN expedition e ON e.id = sl.`code` + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk + GROUP BY sl.scan_id + ) rs ON rs.scan_id = st.id + SET st.lastScanned = rs.lastScanned, + st.routeCount = rs.routeCount, + st.minRoute = rs.minRoute, + st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), + st.scanned = rs.scanned; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; From e8935765911883925cff9ab6a8637f87766d6019 Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 23 Mar 2020 08:24:57 +0100 Subject: [PATCH 09/25] first commit --- .DS_Store | Bin 0 -> 8196 bytes back/.DS_Store | Bin 0 -> 6148 bytes back/methods/.DS_Store | Bin 0 -> 6148 bytes back/methods/collection/collectionGet.js | 22 +++++ back/methods/collection/collectionNew.js | 120 +++++++++++++++++++++++ back/methods/collection/getSectors.js | 20 ++++ back/model-config.json | 3 + back/models/collection.js | 5 + back/models/collection.json | 12 +++ loopback/.DS_Store | Bin 0 -> 6148 bytes 10 files changed, 182 insertions(+) create mode 100644 .DS_Store create mode 100644 back/.DS_Store create mode 100644 back/methods/.DS_Store create mode 100644 back/methods/collection/collectionGet.js create mode 100644 back/methods/collection/collectionNew.js create mode 100644 back/methods/collection/getSectors.js create mode 100644 back/models/collection.js create mode 100644 back/models/collection.json create mode 100644 loopback/.DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..f0821349b2196b034eb2201ebee8f9ea8fe4d886 GIT binary patch literal 8196 zcmeHM(M}UV6ukq*ZVLz)6L@o9OniU_F(Ss8)B+C}F~%BwPy=1Mmddi*bXzLcn!flC z>L2(ieu2N>yC0zE&Mb9yy9J+&kr^^`XLrw;nLTr7rgtGCQEFGO6D<&th0Jz#5=Bbl z=bVSqSajzKtN@?rfLv-)ooeI{q0J4WfKk9GU=%P47zO?X1#o6_vPPWy>ZvJ>0!D#z zsQ~W}HZt2{Wc$j>tpkM&0bnz@Efea910=_eY%#KZWhE7Ds^~#PR1t+3LecTuW;kpy zvVCP0orI#3hYG7IpJM(DCihyPV>%=+ z-lzDGU}k`;@mLeM9|>Ik1UGtAW0eFa3(gURQh{o!ZXY$>X2_umvWxdG=&IrBHHGo< z5o@QjGm?$jisPhGI&KUz<0LSwiH^z0*$Y!O(Q%hz9np5P$Y($ls<>nXglg5MMu^r#+m@DDLppn5l|_HoP^)BG1|tU zpS1SjM+w$_jL65TVjmArxbYcbm13-Ecz_FZi_o23V| zMeDRl52;L>@i9u}^qwqe5#X;e!V_7)Q}IqGY()FYSEu3C!`AZhH!(JznYfU(th|+< z&c7`02c2@O(rSmLO7l5iJ*u?!ov8jK2)seP;ykUpot@ds>w({@)P1)p$@QuW$ctxn zzZ!H(LEEo}vYoPeU|BgUw==uY?cQEnU9?wLS9^h9_x=->4w8s|fzXV)9+aO^8xrQI-1NP`uQ3rhi)|{vQetPqBqwBM2hwGmg4;0K zrJd7w(uH*1944lMC3=9e2KJJiF20s-i#Gju&%CjV@0u%3C0ZE8u9_p2rt>_j?ajyiZ3XE3reom{YnkfMC}cPeE5mWv!9NU9w*h5N dF|vJSaR=$Ie+b}T73TbppS9-vm%ezOieD3RXrcfB literal 0 HcmV?d00001 diff --git a/back/.DS_Store b/back/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a15d86adb3a8380cd195bb108ab8ed68193beb99 GIT binary patch literal 6148 zcmeHK%}(1u5S~raViT!yB@R^T!BP*sa0n_PJz9bEgw(1=pbKp%n^;oh0u4JxEPf=D$Z&3@zgTl=%M>jePO9Y(7F4ggrFgf$z7zX-)i zXQXC4ghKU@5J3@+ii0qn$!5o6WPsk?0(^rQN*KT&?@xvpxegD~q$pdhD^aUAo;+Q! z?8TLn~(>*@#Bv~X!T{+C6Lgkz0%Ki|P1MFkH^1?I4sBPJOXL&qs zciJoN+S}G-#T|D#EwtaPPbRiyy?FiZ#r>{A86pH#mh~XxyRX z(9g3}X8RbKR!y@RnE_^i8JI%`%u;4G=kVV7mYD%&;C>mP^}$6Y^bA%S)zX0j{XSB> zK}do&oh1legPy@kBSuh!E=AO(!W=P#E=Rv>@;rl;MqLg<&5V7_%)*>dgqj`wu1W{t zY2=X^UYk#_~#pYErZX-K6$X3on{wI>1 zw77l|o#lw#->~4-6Ie$Dr~nn90#tws3>C;WJ)I4cjHv(>paM|9z7Hj_Cia2;>A>P6 z0I)&Y4YAJ>z+wqtP3!}afoV{ILDd{FH0a2etgDHAV9-VVWIQKN)|^n(Pe;CZxo8dK zN(HFEqXLuI&aMBi;7{iNM-q2bfC~I81+-bNmkYd7_SVtMS+6bd4cuyOa5KbC!Q$;0 j=m!pwp3eI*>mDrVEV { + Self.remoteMethodCtx('collectionGet', { + description: 'Get pending collections from a worker', + accessType: 'WRITE', + returns: { + type: 'Object', + root: true + }, + http: { + path: `/collectionGet`, + verb: 'POST' + } + }); + + Self.collectionGet = async ctx => { + const userId = ctx.req.accessToken.userId; + const query = `CALL vn.collection_get(?)`; + const [result] = await Self.rawSql(query, [userId]); + + return result; + }; +}; diff --git a/back/methods/collection/collectionNew.js b/back/methods/collection/collectionNew.js new file mode 100644 index 000000000..59830a08b --- /dev/null +++ b/back/methods/collection/collectionNew.js @@ -0,0 +1,120 @@ +module.exports = Self => { + Self.remoteMethodCtx('collectionNew', { + description: 'Make a new collection of tickets', + accessType: 'WRITE', + accepts: [{ + arg: 'collectionFk', + type: 'Number', + required: false, + description: 'The collection id' + }, { + arg: 'sectorFk', + type: 'Number', + required: true, + description: 'The sector of worker' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/collectionNew`, + verb: 'POST' + } + }); + + Self.collectionNew = async(ctx, collectionFk, sectorFk) => { + let query = ''; + + if (!collectionFk) { + const userId = ctx.req.accessToken.userId; + query = `CALL vn.collection_newBeta(?,?)`; + const [result] = await Self.rawSql(query, [sectorFk, userId]); + if (result.length == 0) + throw new Error(`No collections for today`); + + collectionFk = result[0].vCollectionFk; + } + + query = `CALL vn.collectionTicket_get(?)`; + const [tickets] = await Self.rawSql(query, [collectionFk]); + + query = `CALL vn.collectionSale_get(?)`; + const [sales] = await Self.rawSql(query, [collectionFk]); + + query = `CALL vn.collectionPlacement_get(?)`; + const [placements] = await Self.rawSql(query, [collectionFk]); + + return makeCollection(tickets, sales, placements); + }; + + /** + * Returns a collection json + * @param {*} tickets - Request tickets + * @param {*} sales - Request sales + * @param {*} placements - Request placements + * @return {Object} Collection JSON + */ + async function makeCollection(tickets, sales, placements) { + let collection = []; + + for (let i = 0; i < tickets.length; i++) { + let ticket = {}; + ticket['ticketFk'] = tickets[i]['ticketFk']; + ticket['level'] = tickets[i]['level']; + ticket['agencyName'] = tickets[i]['agencyName']; + ticket['warehouseFk'] = tickets[i]['warehouseFk']; + ticket['salesPersonFk'] = tickets[i]['salesPersonFk']; + + let ticketSales = []; + + for (let x = 0; x < sales.length; x++) { + if (sales[x]['ticketFk'] == ticket['ticketFk']) { + let sale = {}; + + sale['ticketFk'] = sales[x]['ticketFk']; + sale['saleFk'] = sales[x]['saleFk']; + sale['itemFk'] = sales[x]['itemFk']; + sale['quantity'] = sales[x]['quantity']; + sale['longName'] = sales[x]['longName']; + sale['size'] = sales[x]['size']; + sale['color'] = sales[x]['color']; + sale['discount'] = sales[x]['discount']; + sale['price'] = sales[x]['price']; + sale['stems'] = sales[x]['stems']; + sale['category'] = sales[x]['category']; + sale['origin'] = sales[x]['origin']; + sale['clientFk'] = sales[x]['clientFk']; + sale['productor'] = sales[x]['productor']; + sale['reserved'] = sales[x]['reserved']; + sale['isPreviousPrepared'] = sales[x]['isPreviousPrepared']; + sale['isPrepared'] = sales[x]['isPrepared']; + sale['isControlled'] = sales[x]['isControlled']; + + let salePlacements = []; + + for (let z = 0; z < placements.length; z++) { + if (placements[z]['saleFk'] == sale['saleFk']) { + let placement = {}; + placement['saleFk'] = placements[z]['saleFk']; + placement['itemFk'] = placements[z]['itemFk']; + placement['placement'] = placements[z]['placement']; + placement['shelving'] = placements[z]['shelving']; + placement['created'] = placements[z]['created']; + placement['visible'] = placements[z]['visible']; + placement['order'] = placements[z]['order']; + placement['grouping'] = placements[z]['grouping']; + salePlacements.push(placement); + } + } + sale['placements'] = salePlacements; + ticketSales.push(sale); + } + } + ticket['sales'] = ticketSales; + collection.push(ticket); + } + + return collection; + } +}; diff --git a/back/methods/collection/getSectors.js b/back/methods/collection/getSectors.js new file mode 100644 index 000000000..c5da7ec13 --- /dev/null +++ b/back/methods/collection/getSectors.js @@ -0,0 +1,20 @@ +module.exports = Self => { + Self.remoteMethodCtx('getSectors', { + description: 'Get all sectors', + accessType: 'WRITE', + returns: { + type: 'Object', + root: true + }, + http: { + path: `/getSectors`, + verb: 'POST' + } + }); + + Self.getSectors = async ctx => { + const query = `CALL vn.sector_get()`; + const [result] = await Self.rawSql(query, []); + return result; + }; +}; diff --git a/back/model-config.json b/back/model-config.json index 50603be3f..872f2239e 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -14,6 +14,9 @@ "Container": { "dataSource": "storage" }, + "Collection": { + "dataSource": "vn" + }, "Chat": { "dataSource": "vn" }, diff --git a/back/models/collection.js b/back/models/collection.js new file mode 100644 index 000000000..2802425a5 --- /dev/null +++ b/back/models/collection.js @@ -0,0 +1,5 @@ +module.exports = Self => { + require('../methods/collection/collectionGet')(Self); + require('../methods/collection/collectionNew')(Self); + require('../methods/collection/getSectors')(Self); +}; diff --git a/back/models/collection.json b/back/models/collection.json new file mode 100644 index 000000000..3e428ef60 --- /dev/null +++ b/back/models/collection.json @@ -0,0 +1,12 @@ +{ + "name": "Collection", + "base": "VnModel", + "acls": [{ + "property": "validations", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} + \ No newline at end of file diff --git a/loopback/.DS_Store b/loopback/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5eff1eaf067fb52e1e272e187642d76f154ecfcf GIT binary patch literal 6148 zcmeHK!EVz)5S>j;>I4uuAhkzdkT^tDT0|&9NNGq9Js=^B-~gz#W2-fFy;1Bmf)L~j z9|3>Br|<=Q2p<4%b{AA9z<~oo(M~k;c4udHz0cWQFA<6UB-$ow5s?dJbeb@~5N>B( zlA7^wqfmWF$_`RF3{x2{MO%kuz%uZ^F~DoLPD7G(hF^94@}_VPdh?qS_2_j<5jCU$ z7++ZH9Q$b@_6m&6Y8V~S~uUQxb0hS*rhYtUobr#%|bL*N#kE2@qp-Y;a-(Qiy+ zI%m5O`}I$;;WQta-Rg5VN|U_kbiRn%nsceX?z&C4dA0e{Kao?v2#QJG55~{A_9!S$ zLQ{SsW%{!mgin)rdf2-DKxRddWbs%fCsB-$7tfL`lGDDNWKpjA@pXgiHr&QxYjZZc zyW4GhJKgTQ?ag*~ZnwQVom=yH!`-;CegEL-?Dd=3+xfc>m=Hu@%T;pC;1BqSLWPiX zf1ITadRG>~3=87S7I{coA>lrLH>U0w3@*&K~!rV}V z8Xf(6Dx5@5qqUX+%RrTZHC=7-`M>}B`+qgb)+_^-ft6xFI0Jvs$CS+3x->aHYdz=@ ql!fC;jVcAk9LK7_NAV_93EDg^0DA^YjqpJ1hk&BN8q2^xW#Buj-=0PQ literal 0 HcmV?d00001 From 60d80502d16c6823430b0f9f98ecfe88f2bde3e2 Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 23 Mar 2020 10:36:10 +0100 Subject: [PATCH 10/25] collection update sale --- .../collection/collectionUpdateSale.js | 42 +++++++++++++++++++ back/models/collection.js | 1 + 2 files changed, 43 insertions(+) create mode 100644 back/methods/collection/collectionUpdateSale.js diff --git a/back/methods/collection/collectionUpdateSale.js b/back/methods/collection/collectionUpdateSale.js new file mode 100644 index 000000000..4e8775755 --- /dev/null +++ b/back/methods/collection/collectionUpdateSale.js @@ -0,0 +1,42 @@ +module.exports = Self => { + Self.remoteMethodCtx('collectionUpdateSale', { + description: 'Update sale of a collection', + accessType: 'WRITE', + accepts: [{ + arg: 'sale', + type: 'Number', + required: true, + description: 'The sale id' + }, { + arg: 'originalQuantity', + type: 'Number', + required: true, + description: 'The quantity to sale' + }, { + arg: 'ticketFk', + type: 'Number', + required: true, + description: 'The ticket id' + }, { + arg: 'stateFk', + type: 'Number', + required: true, + description: 'The state id' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/collectionUpdateSale`, + verb: 'POST' + } + }); + + Self.collectionUpdateSale = async(ctx, sale, originalQuantity, ticketFk, stateFk) => { + const userId = ctx.req.accessToken.userId; + + query = `vn.collection_updateSale(?,?,?,?,?)`; + return await Self.rawSql(query, [sale, originalQuantity, userId, stateFk, ticketFk]); + }; +}; diff --git a/back/models/collection.js b/back/models/collection.js index 2802425a5..9f944d72f 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -2,4 +2,5 @@ module.exports = Self => { require('../methods/collection/collectionGet')(Self); require('../methods/collection/collectionNew')(Self); require('../methods/collection/getSectors')(Self); + require('../methods/collection/collectionUpdateSale')(Self); }; From 6829adc89707c022522a1e953cd7c825a8c6ad64 Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 23 Mar 2020 13:26:45 +0100 Subject: [PATCH 11/25] faults --- back/methods/collection/collectionFaults.js | 35 +++++++++++++++++++++ back/methods/collection/collectionNew.js | 3 ++ back/models/collection.js | 1 + 3 files changed, 39 insertions(+) create mode 100644 back/methods/collection/collectionFaults.js diff --git a/back/methods/collection/collectionFaults.js b/back/methods/collection/collectionFaults.js new file mode 100644 index 000000000..b39e9f2d2 --- /dev/null +++ b/back/methods/collection/collectionFaults.js @@ -0,0 +1,35 @@ +module.exports = Self => { + Self.remoteMethodCtx('collectionFaults', { + description: 'Update sale of a collection', + accessType: 'WRITE', + accepts: [{ + arg: 'shelvingFk', + type: 'Number', + required: true, + description: 'The sale id' + }, { + arg: 'quantity', + type: 'Number', + required: true, + description: 'The quantity to sale' + }, { + arg: 'itemFk', + type: 'Number', + required: true, + description: 'The ticket id' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/collectionFaults`, + verb: 'POST' + } + }); + + Self.collectionFaults = async(ctx, shelvingFk, quantity, itemFk) => { + query = `vn.collection_faults(?,?,?)`; + return await Self.rawSql(query, [shelvingFk, quantity, itemFk]); + }; +}; diff --git a/back/methods/collection/collectionNew.js b/back/methods/collection/collectionNew.js index 59830a08b..6e248f640 100644 --- a/back/methods/collection/collectionNew.js +++ b/back/methods/collection/collectionNew.js @@ -45,6 +45,9 @@ module.exports = Self => { query = `CALL vn.collectionPlacement_get(?)`; const [placements] = await Self.rawSql(query, [collectionFk]); + query = `CALL vn.collectionSticker_print(?,?)`; + // await Self.rawSql(query, [collectionFk, sectorFk]); + return makeCollection(tickets, sales, placements); }; diff --git a/back/models/collection.js b/back/models/collection.js index 9f944d72f..aad0b4196 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -3,4 +3,5 @@ module.exports = Self => { require('../methods/collection/collectionNew')(Self); require('../methods/collection/getSectors')(Self); require('../methods/collection/collectionUpdateSale')(Self); + require('../methods/collection/collectionFaults')(Self); }; From 4927ea4ca756302d4fa7e72174f6b99366c1cd77 Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 23 Mar 2020 15:22:48 +0100 Subject: [PATCH 12/25] sacadores --- back/methods/collection/collectionFaults.js | 6 +++--- back/methods/collection/collectionNew.js | 17 +++++++++++------ back/methods/collection/collectionUpdateSale.js | 2 +- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/back/methods/collection/collectionFaults.js b/back/methods/collection/collectionFaults.js index b39e9f2d2..ac5186575 100644 --- a/back/methods/collection/collectionFaults.js +++ b/back/methods/collection/collectionFaults.js @@ -4,9 +4,9 @@ module.exports = Self => { accessType: 'WRITE', accepts: [{ arg: 'shelvingFk', - type: 'Number', + type: 'String', required: true, - description: 'The sale id' + description: 'The shalving id' }, { arg: 'quantity', type: 'Number', @@ -29,7 +29,7 @@ module.exports = Self => { }); Self.collectionFaults = async(ctx, shelvingFk, quantity, itemFk) => { - query = `vn.collection_faults(?,?,?)`; + query = `CALL vn.collection_faults(?,?,?)`; return await Self.rawSql(query, [shelvingFk, quantity, itemFk]); }; }; diff --git a/back/methods/collection/collectionNew.js b/back/methods/collection/collectionNew.js index 6e248f640..9a3020bf8 100644 --- a/back/methods/collection/collectionNew.js +++ b/back/methods/collection/collectionNew.js @@ -12,6 +12,11 @@ module.exports = Self => { type: 'Number', required: true, description: 'The sector of worker' + }, { + arg: 'vWagons', + type: 'Number', + required: true, + description: 'The number of wagons' }], returns: { type: 'Object', @@ -23,13 +28,13 @@ module.exports = Self => { } }); - Self.collectionNew = async(ctx, collectionFk, sectorFk) => { + Self.collectionNew = async(ctx, collectionFk, sectorFk, vWagons) => { let query = ''; if (!collectionFk) { const userId = ctx.req.accessToken.userId; - query = `CALL vn.collection_newBeta(?,?)`; - const [result] = await Self.rawSql(query, [sectorFk, userId]); + query = `CALL vn.collectionTrain_newBeta(?,?,?)`; + const [result] = await Self.rawSql(query, [sectorFk, vWagons, userId]); if (result.length == 0) throw new Error(`No collections for today`); @@ -48,7 +53,7 @@ module.exports = Self => { query = `CALL vn.collectionSticker_print(?,?)`; // await Self.rawSql(query, [collectionFk, sectorFk]); - return makeCollection(tickets, sales, placements); + return makeCollection(tickets, sales, placements, collectionFk); }; /** @@ -58,7 +63,7 @@ module.exports = Self => { * @param {*} placements - Request placements * @return {Object} Collection JSON */ - async function makeCollection(tickets, sales, placements) { + async function makeCollection(tickets, sales, placements, collectionFk) { let collection = []; for (let i = 0; i < tickets.length; i++) { @@ -74,7 +79,7 @@ module.exports = Self => { for (let x = 0; x < sales.length; x++) { if (sales[x]['ticketFk'] == ticket['ticketFk']) { let sale = {}; - + sale['collectionFk'] = collectionFk; sale['ticketFk'] = sales[x]['ticketFk']; sale['saleFk'] = sales[x]['saleFk']; sale['itemFk'] = sales[x]['itemFk']; diff --git a/back/methods/collection/collectionUpdateSale.js b/back/methods/collection/collectionUpdateSale.js index 4e8775755..7204dad22 100644 --- a/back/methods/collection/collectionUpdateSale.js +++ b/back/methods/collection/collectionUpdateSale.js @@ -36,7 +36,7 @@ module.exports = Self => { Self.collectionUpdateSale = async(ctx, sale, originalQuantity, ticketFk, stateFk) => { const userId = ctx.req.accessToken.userId; - query = `vn.collection_updateSale(?,?,?,?,?)`; + query = `CALL vn.collection_updateSale(?,?,?,?,?)`; return await Self.rawSql(query, [sale, originalQuantity, userId, stateFk, ticketFk]); }; }; From 1063db3a2f473b270ddc64d2889b6f78fb1068e9 Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 23 Mar 2020 15:34:13 +0100 Subject: [PATCH 13/25] print --- back/methods/collection/collectionNew.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/back/methods/collection/collectionNew.js b/back/methods/collection/collectionNew.js index 9a3020bf8..d22a0b7fe 100644 --- a/back/methods/collection/collectionNew.js +++ b/back/methods/collection/collectionNew.js @@ -51,7 +51,7 @@ module.exports = Self => { const [placements] = await Self.rawSql(query, [collectionFk]); query = `CALL vn.collectionSticker_print(?,?)`; - // await Self.rawSql(query, [collectionFk, sectorFk]); + await Self.rawSql(query, [collectionFk, sectorFk]); return makeCollection(tickets, sales, placements, collectionFk); }; @@ -61,6 +61,7 @@ module.exports = Self => { * @param {*} tickets - Request tickets * @param {*} sales - Request sales * @param {*} placements - Request placements + * @param {*} collectionFk - Request placements * @return {Object} Collection JSON */ async function makeCollection(tickets, sales, placements, collectionFk) { From 07d952646a0bd953b3861c1f367a9f395e8fa239 Mon Sep 17 00:00:00 2001 From: Ainki Date: Thu, 26 Mar 2020 13:12:59 +0100 Subject: [PATCH 14/25] change some names an methods --- back/methods/collection/collectionFaults.js | 4 +- .../collection/collectionUpdateSale.js | 42 --------- .../{collectionGet.js => getCollection.js} | 10 +-- back/methods/collection/getSectors.js | 4 +- .../{collectionNew.js => newCollection.js} | 10 ++- .../collection/updateCollectionSale.js | 89 +++++++++++++++++++ back/models/collection.js | 6 +- 7 files changed, 108 insertions(+), 57 deletions(-) delete mode 100644 back/methods/collection/collectionUpdateSale.js rename back/methods/collection/{collectionGet.js => getCollection.js} (69%) rename back/methods/collection/{collectionNew.js => newCollection.js} (93%) create mode 100644 back/methods/collection/updateCollectionSale.js diff --git a/back/methods/collection/collectionFaults.js b/back/methods/collection/collectionFaults.js index ac5186575..395c7e581 100644 --- a/back/methods/collection/collectionFaults.js +++ b/back/methods/collection/collectionFaults.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('collectionFaults', { + Self.remoteMethod('collectionFaults', { description: 'Update sale of a collection', accessType: 'WRITE', accepts: [{ @@ -28,7 +28,7 @@ module.exports = Self => { } }); - Self.collectionFaults = async(ctx, shelvingFk, quantity, itemFk) => { + Self.collectionFaults = async(shelvingFk, quantity, itemFk) => { query = `CALL vn.collection_faults(?,?,?)`; return await Self.rawSql(query, [shelvingFk, quantity, itemFk]); }; diff --git a/back/methods/collection/collectionUpdateSale.js b/back/methods/collection/collectionUpdateSale.js deleted file mode 100644 index 7204dad22..000000000 --- a/back/methods/collection/collectionUpdateSale.js +++ /dev/null @@ -1,42 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('collectionUpdateSale', { - description: 'Update sale of a collection', - accessType: 'WRITE', - accepts: [{ - arg: 'sale', - type: 'Number', - required: true, - description: 'The sale id' - }, { - arg: 'originalQuantity', - type: 'Number', - required: true, - description: 'The quantity to sale' - }, { - arg: 'ticketFk', - type: 'Number', - required: true, - description: 'The ticket id' - }, { - arg: 'stateFk', - type: 'Number', - required: true, - description: 'The state id' - }], - returns: { - type: 'Object', - root: true - }, - http: { - path: `/collectionUpdateSale`, - verb: 'POST' - } - }); - - Self.collectionUpdateSale = async(ctx, sale, originalQuantity, ticketFk, stateFk) => { - const userId = ctx.req.accessToken.userId; - - query = `CALL vn.collection_updateSale(?,?,?,?,?)`; - return await Self.rawSql(query, [sale, originalQuantity, userId, stateFk, ticketFk]); - }; -}; diff --git a/back/methods/collection/collectionGet.js b/back/methods/collection/getCollection.js similarity index 69% rename from back/methods/collection/collectionGet.js rename to back/methods/collection/getCollection.js index ff98c55d5..caf9cc521 100644 --- a/back/methods/collection/collectionGet.js +++ b/back/methods/collection/getCollection.js @@ -1,18 +1,18 @@ module.exports = Self => { - Self.remoteMethodCtx('collectionGet', { + Self.remoteMethodCtx('getCollection', { description: 'Get pending collections from a worker', - accessType: 'WRITE', + accessType: 'READ', returns: { type: 'Object', root: true }, http: { - path: `/collectionGet`, - verb: 'POST' + path: `/getCollection`, + verb: 'GET' } }); - Self.collectionGet = async ctx => { + Self.getCollection = async ctx => { const userId = ctx.req.accessToken.userId; const query = `CALL vn.collection_get(?)`; const [result] = await Self.rawSql(query, [userId]); diff --git a/back/methods/collection/getSectors.js b/back/methods/collection/getSectors.js index c5da7ec13..d844e5097 100644 --- a/back/methods/collection/getSectors.js +++ b/back/methods/collection/getSectors.js @@ -1,14 +1,14 @@ module.exports = Self => { Self.remoteMethodCtx('getSectors', { description: 'Get all sectors', - accessType: 'WRITE', + accessType: 'READ', returns: { type: 'Object', root: true }, http: { path: `/getSectors`, - verb: 'POST' + verb: 'GET' } }); diff --git a/back/methods/collection/collectionNew.js b/back/methods/collection/newCollection.js similarity index 93% rename from back/methods/collection/collectionNew.js rename to back/methods/collection/newCollection.js index d22a0b7fe..31e419b67 100644 --- a/back/methods/collection/collectionNew.js +++ b/back/methods/collection/newCollection.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('collectionNew', { + Self.remoteMethodCtx('newCollection', { description: 'Make a new collection of tickets', accessType: 'WRITE', accepts: [{ @@ -23,12 +23,12 @@ module.exports = Self => { root: true }, http: { - path: `/collectionNew`, + path: `/newCollection`, verb: 'POST' } }); - Self.collectionNew = async(ctx, collectionFk, sectorFk, vWagons) => { + Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => { let query = ''; if (!collectionFk) { @@ -85,6 +85,10 @@ module.exports = Self => { sale['saleFk'] = sales[x]['saleFk']; sale['itemFk'] = sales[x]['itemFk']; sale['quantity'] = sales[x]['quantity']; + if (sales[x]['quantityPicked'] != null) + sale['quantityPicked'] = sales[x]['quantityPicked']; + else + sale['quantityPicked'] = 0; sale['longName'] = sales[x]['longName']; sale['size'] = sales[x]['size']; sale['color'] = sales[x]['color']; diff --git a/back/methods/collection/updateCollectionSale.js b/back/methods/collection/updateCollectionSale.js new file mode 100644 index 000000000..01575c972 --- /dev/null +++ b/back/methods/collection/updateCollectionSale.js @@ -0,0 +1,89 @@ +module.exports = Self => { + Self.remoteMethodCtx('updateCollectionSale', { + description: 'Update sale of a collection', + accessType: 'WRITE', + accepts: [{ + arg: 'sale', + type: 'Number', + required: true, + description: 'The sale id' + }, { + arg: 'originalQuantity', + type: 'Number', + required: true, + description: 'The quantity to sale' + }, + { + arg: 'quantity', + type: 'Number', + required: true, + description: 'The quantity to picked' + }, + { + arg: 'quantityPicked', + type: 'Number', + required: true, + description: 'The quantity to picked' + }, { + arg: 'ticketFk', + type: 'Number', + required: true, + description: 'The ticket id' + }, { + arg: 'stateFk', + type: 'Number', + required: true, + description: 'The state id' + }, { + arg: 'isNicho', + type: 'Boolean', + required: true, + description: 'Determine if sale is picked from nicho or not' + }, { + arg: 'shelvingFk', + type: 'String', + required: false, + description: 'The shelving id' + }, { + arg: 'itemFk', + type: 'Number', + required: true, + description: 'The item id' + }, { + arg: 'sectorFk', + type: 'Number', + required: true, + description: 'The sector id' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/updateCollectionSale`, + verb: 'POST' + } + }); + + Self.updateCollectionSale = async(ctx, sale, originalQuantity, quantity, quantityPicked, ticketFk, stateFk, isNicho, shelvingFk, itemFk, sectorFk) => { + const userId = ctx.req.accessToken.userId; + + if (originalQuantity == quantity) { + query = `CALL vn.collection_updateSale(?,?,?,?,?)`; + await Self.rawSql(query, [sale, originalQuantity, userId, stateFk, ticketFk]); + } + + if (!isNicho) { + query = `CALL vn.collection_faults(?,?,?)`; + await Self.rawSql(query, [shelvingFk, quantityPicked, itemFk]); + } else { + query = `CALL vn.sector_getWarehouse(?)`; + const [result] = await Self.rawSql(query, [sectorFk]); + + query = `CALL vn.itemPlacementSave(?,?,?)`; + await Self.rawSql(query, [shelvingFk, quantityPicked, result[0]['warehouseFk']]); + } + query = `CALL vn.sale_updateOriginalQuantity(?,?)`; + return await Self.rawSql(query, [sale, quantity]); + }; +}; diff --git a/back/models/collection.js b/back/models/collection.js index aad0b4196..d3670d56b 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -1,7 +1,7 @@ module.exports = Self => { - require('../methods/collection/collectionGet')(Self); - require('../methods/collection/collectionNew')(Self); + require('../methods/collection/getCollection')(Self); + require('../methods/collection/newCollection')(Self); require('../methods/collection/getSectors')(Self); - require('../methods/collection/collectionUpdateSale')(Self); + require('../methods/collection/updateCollectionSale')(Self); require('../methods/collection/collectionFaults')(Self); }; From fceee0a9d66baa0ec4db1bf5b041e5ba955874a5 Mon Sep 17 00:00:00 2001 From: Ainki Date: Thu, 26 Mar 2020 19:10:09 +0100 Subject: [PATCH 15/25] spec --- back/methods/collection/getSectors.js | 6 +++--- back/methods/collection/spec/collectionFauls.spec.js | 8 ++++++++ back/methods/collection/spec/getCollection.spec.js | 10 ++++++++++ back/methods/collection/spec/getSectors.spec.js | 9 +++++++++ back/methods/collection/spec/newCollection.spec.js | 10 ++++++++++ .../collection/spec/updateCollectionSale.spec.js | 7 +++++++ 6 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 back/methods/collection/spec/collectionFauls.spec.js create mode 100644 back/methods/collection/spec/getCollection.spec.js create mode 100644 back/methods/collection/spec/getSectors.spec.js create mode 100644 back/methods/collection/spec/newCollection.spec.js create mode 100644 back/methods/collection/spec/updateCollectionSale.spec.js diff --git a/back/methods/collection/getSectors.js b/back/methods/collection/getSectors.js index d844e5097..12ad0dc06 100644 --- a/back/methods/collection/getSectors.js +++ b/back/methods/collection/getSectors.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('getSectors', { + Self.remoteMethod('getSectors', { description: 'Get all sectors', accessType: 'READ', returns: { @@ -12,9 +12,9 @@ module.exports = Self => { } }); - Self.getSectors = async ctx => { + Self.getSectors = async() => { const query = `CALL vn.sector_get()`; - const [result] = await Self.rawSql(query, []); + const [result] = await Self.rawSql(query); return result; }; }; diff --git a/back/methods/collection/spec/collectionFauls.spec.js b/back/methods/collection/spec/collectionFauls.spec.js new file mode 100644 index 000000000..0df234bfd --- /dev/null +++ b/back/methods/collection/spec/collectionFauls.spec.js @@ -0,0 +1,8 @@ + +describe('collectionFaults()', () => { + it('return shelving afected', async() => { + let val = 2; + + expect(val).toBeGreaterThan(1); + }); +}); diff --git a/back/methods/collection/spec/getCollection.spec.js b/back/methods/collection/spec/getCollection.spec.js new file mode 100644 index 000000000..b8a92285f --- /dev/null +++ b/back/methods/collection/spec/getCollection.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('getCollection()', () => { + it('return list of collection', async() => { + let ctx = {req: {accessToken: {userId: 1}}}; + let response = await app.models.Collection.getCollection(ctx); + + expect(response.length).toEqual(0); + }); +}); diff --git a/back/methods/collection/spec/getSectors.spec.js b/back/methods/collection/spec/getSectors.spec.js new file mode 100644 index 000000000..4ba288c01 --- /dev/null +++ b/back/methods/collection/spec/getSectors.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('getSectors()', () => { + it('return list of sectors', async() => { + let response = await app.models.Collection.getSectors(); + + expect(response.length).toBeGreaterThan(0); + }); +}); diff --git a/back/methods/collection/spec/newCollection.spec.js b/back/methods/collection/spec/newCollection.spec.js new file mode 100644 index 000000000..4bf3f7945 --- /dev/null +++ b/back/methods/collection/spec/newCollection.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('newCollection()', () => { + it('return a new collection', async() => { + let ctx = {req: {accessToken: {userId: 1}}}; + let response = await app.models.Collection.newCollection(ctx, 500, 1, 1); + + expect(response.length).toBeGreaterThan(0); + }); +}); diff --git a/back/methods/collection/spec/updateCollectionSale.spec.js b/back/methods/collection/spec/updateCollectionSale.spec.js new file mode 100644 index 000000000..bd4d0fb78 --- /dev/null +++ b/back/methods/collection/spec/updateCollectionSale.spec.js @@ -0,0 +1,7 @@ +describe('updateCollectionSale()', () => { + it('return a collection updated', async() => { + let val = 2; + + expect(val).toBeGreaterThan(1); + }); +}); From ec630d6a7ba1a9f552bcbacb611297bae7399c18 Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 30 Mar 2020 14:28:29 +0200 Subject: [PATCH 16/25] cherry-pick --- .../collection/spec/collectionFauls.spec.js | 7 +- .../collection/spec/getCollection.spec.js | 5 +- .../collection/spec/getSectors.spec.js | 2 + .../collection/spec/newCollection.spec.js | 5 +- .../spec/updateCollectionSale.spec.js | 13 ++- .../00-collectionPlacement_get.sql | 108 ++++++++++++++++++ .../00-collection_faults.sql | 39 +++++++ .../00-collection_updateSale.sql | 42 +++++++ .../00-coolerPathDetail.sql | 13 +++ .../00-sale_updateOriginalQuantity.sql | 15 +++ .../00-sector_getWarehouse.sql | 14 +++ 11 files changed, 252 insertions(+), 11 deletions(-) create mode 100644 db/changes/10162-postValentineDay/00-collectionPlacement_get.sql create mode 100644 db/changes/10162-postValentineDay/00-collection_faults.sql create mode 100644 db/changes/10162-postValentineDay/00-collection_updateSale.sql create mode 100644 db/changes/10162-postValentineDay/00-coolerPathDetail.sql create mode 100644 db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql create mode 100644 db/changes/10162-postValentineDay/00-sector_getWarehouse.sql diff --git a/back/methods/collection/spec/collectionFauls.spec.js b/back/methods/collection/spec/collectionFauls.spec.js index 0df234bfd..210dcdf63 100644 --- a/back/methods/collection/spec/collectionFauls.spec.js +++ b/back/methods/collection/spec/collectionFauls.spec.js @@ -1,8 +1,9 @@ - +const app = require('vn-loopback/server/server'); describe('collectionFaults()', () => { it('return shelving afected', async() => { - let val = 2; + let response = await app.models.Collection.collectionFaults('UXN', 0, 1); - expect(val).toBeGreaterThan(1); + expect(response.length).toBeGreaterThan(0); + expect(response[0][0].shelvingFk).toEqual('UXN'); }); }); diff --git a/back/methods/collection/spec/getCollection.spec.js b/back/methods/collection/spec/getCollection.spec.js index b8a92285f..44c7af62f 100644 --- a/back/methods/collection/spec/getCollection.spec.js +++ b/back/methods/collection/spec/getCollection.spec.js @@ -2,9 +2,10 @@ const app = require('vn-loopback/server/server'); describe('getCollection()', () => { it('return list of collection', async() => { - let ctx = {req: {accessToken: {userId: 1}}}; + let ctx = {req: {accessToken: {userId: 106}}}; let response = await app.models.Collection.getCollection(ctx); - expect(response.length).toEqual(0); + expect(response.length).toBeGreaterThan(0); + expect(response[0].collectionFk).toEqual(1); }); }); diff --git a/back/methods/collection/spec/getSectors.spec.js b/back/methods/collection/spec/getSectors.spec.js index 4ba288c01..d453220a0 100644 --- a/back/methods/collection/spec/getSectors.spec.js +++ b/back/methods/collection/spec/getSectors.spec.js @@ -5,5 +5,7 @@ describe('getSectors()', () => { let response = await app.models.Collection.getSectors(); expect(response.length).toBeGreaterThan(0); + expect(response[0].id).toEqual(1); + expect(response[0].description).toEqual('First sector'); }); }); diff --git a/back/methods/collection/spec/newCollection.spec.js b/back/methods/collection/spec/newCollection.spec.js index 4bf3f7945..bd574db0f 100644 --- a/back/methods/collection/spec/newCollection.spec.js +++ b/back/methods/collection/spec/newCollection.spec.js @@ -2,9 +2,10 @@ const app = require('vn-loopback/server/server'); describe('newCollection()', () => { it('return a new collection', async() => { - let ctx = {req: {accessToken: {userId: 1}}}; - let response = await app.models.Collection.newCollection(ctx, 500, 1, 1); + let ctx = {req: {accessToken: {userId: 106}}}; + let response = await app.models.Collection.newCollection(ctx, 1, 1, 1); expect(response.length).toBeGreaterThan(0); + expect(response[0].ticketFk).toEqual(1); }); }); diff --git a/back/methods/collection/spec/updateCollectionSale.spec.js b/back/methods/collection/spec/updateCollectionSale.spec.js index bd4d0fb78..4695f6eec 100644 --- a/back/methods/collection/spec/updateCollectionSale.spec.js +++ b/back/methods/collection/spec/updateCollectionSale.spec.js @@ -1,7 +1,12 @@ -describe('updateCollectionSale()', () => { - it('return a collection updated', async() => { - let val = 2; +const app = require('vn-loopback/server/server'); - expect(val).toBeGreaterThan(1); +describe('updateCollectionSale()', () => { + it('return a new collection', async() => { + let ctx = {req: {accessToken: {userId: 106}}}; + let response = await app.models.Collection.updateCollectionSale(ctx, 1, 5, 5, 5, 1, 4, false, 'UXN', 1, 1); + + expect(response.length).toBeGreaterThan(0); + expect(response[0][0].id).toEqual(1); + expect(response[0][0].quantity).toEqual(5); }); }); diff --git a/db/changes/10162-postValentineDay/00-collectionPlacement_get.sql b/db/changes/10162-postValentineDay/00-collectionPlacement_get.sql new file mode 100644 index 000000000..d89f6a801 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-collectionPlacement_get.sql @@ -0,0 +1,108 @@ +DROP procedure IF EXISTS `vn`.`collectionPlacement_get`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`collectionPlacement_get`(vCollectionFk INT) +BEGIN + + DECLARE vCalcFk INT; + DECLARE vWarehouseFk INT; + DECLARE vWarehouseAliasFk INT; + + SELECT t.warehouseFk, w.aliasFk + INTO vWarehouseFk, vWarehouseAliasFk + FROM vn.ticket t + JOIN vn.ticketCollection tc ON tc.ticketFk = t.id + JOIN vn.warehouse w ON w.id = t.warehouseFk + WHERE tc.collectionFk = vCollectionFk + LIMIT 1; + + CALL cache.visible_refresh(vCalcFk,FALSE,vWarehouseFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.parked; + CREATE TEMPORARY TABLE tmp.parked + ENGINE MEMORY + SELECT s.itemFk, 0 as quantity + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk; + + UPDATE tmp.parked pk + JOIN ( SELECT itemFk, sum(visible) as visible + FROM vn.itemShelvingStock iss + JOIN vn.warehouse w ON w.id = iss.warehouseFk + WHERE w.aliasFk = vWarehouseAliasFk + GROUP BY iss.itemFk ) iss ON iss.itemFk = pk.itemFk + SET pk.quantity = iss.visible; + + DROP TEMPORARY TABLE IF EXISTS tmp.`grouping`; + CREATE TEMPORARY TABLE tmp.`grouping` + ENGINE MEMORY + SELECT itemFk, `grouping` + FROM ( + SELECT itemFk, + CASE groupingMode + WHEN 0 THEN 1 + WHEN 2 THEN packing + ELSE `grouping` + END AS `grouping` + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseInFk = vWarehouseFk + AND landed BETWEEN (SELECT inventoried FROM vn.config LIMIT 1) AND CURDATE() + AND b.isIgnored = FALSE + ORDER BY tr.landed DESC + ) sub + GROUP BY sub.itemFk ; + + DROP TEMPORARY TABLE IF EXISTS tmp.grouping2; + CREATE TEMPORARY TABLE tmp.grouping2 + ENGINE MEMORY + SELECT * FROM tmp.`grouping`; + + + SELECT s.id as saleFk, s.itemFk, + p.code COLLATE utf8_general_ci as placement , + sh.code COLLATE utf8_general_ci as shelving, + ish.created, + ish.visible, + 0 as `order`, + IF(sc.isPreviousPreparedByPacking, ish.packing, g.`grouping`) as `grouping` + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector sc ON sc.id = p.sectorFk + JOIN vn.warehouse w ON w.id = sc.warehouseFk + JOIN tmp.`grouping` g ON g.itemFk = s.itemFk + WHERE tc.collectionFk = vCollectionFk + AND w.aliasFk = vWarehouseAliasFk + AND ish.visible > 0 + UNION ALL + SELECT s.id as saleFk, s.itemFk, + ip.code COLLATE utf8_general_ci as placement, + '' COLLATE latin1_general_ci as shelving, + modificationDate as created, + v.visible - p.quantity as visible, + 0 as `order`, + g.`grouping` + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.itemPlacement ip ON ip.itemFk = s.itemFk AND ip.warehouseFk = vWarehouseFk + JOIN tmp.parked p ON p.itemFk = s.itemFk + JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vCalcFk + LEFT JOIN tmp.grouping2 g ON g.itemFk = s.itemFk + WHERE tc.collectionFk = vCollectionFk + AND v.visible - p.quantity > 0; + + DROP TEMPORARY TABLE + tmp.parked, + tmp.`grouping`, + tmp.grouping2; +END + + +$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-collection_faults.sql b/db/changes/10162-postValentineDay/00-collection_faults.sql new file mode 100644 index 000000000..5faa42ca4 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-collection_faults.sql @@ -0,0 +1,39 @@ +DROP procedure IF EXISTS `vn`.`collection_faults`; + +DELIMITER $$ + +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`collection_faults`( + vShelvingFk VARCHAR(10), + vQuantity INT, + vItemFk INT) +BEGIN + DECLARE vQuantityTotal INT DEFAULT 0; + DECLARE vshelve VARCHAR(2); + DECLARE vdeep INT(11); + DECLARE vpriority INT(11); + DECLARE vgrouping SMALLINT(5); + DECLARE vpacking INT(11); + DECLARE vpackagingFk VARCHAR(10); + DECLARE vlevel VARCHAR(45); + DECLARE vuserFk INT(10); + + + SELECT SUM(quantity),shelve,deep,priority,`grouping`,packing,packagingFk,`level`,userFk + INTO vQuantityTotal,vshelve,vdeep,vpriority,vgrouping,vpacking,vpackagingFk,vlevel,vuserFk + FROM vn.itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk + GROUP BY itemFk; + + SELECT vQuantityTotal - vQuantity INTO vQuantityTotal; + + DELETE FROM vn.itemShelving WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk; + + INSERT INTO vn.itemShelving (itemFk, shelvingFk,shelve,deep,quantity,visible,available,priority,`grouping`,packing,packagingFk,`level`,userFk ) + VALUES (vItemFk,vShelvingFk,vshelve,vdeep,vQuantityTotal,vQuantityTotal,vQuantityTotal,vpriority,vgrouping,vpacking,vpackagingFk,vlevel,vuserFk ); + + SELECT * FROM vn.itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk; + +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-collection_updateSale.sql b/db/changes/10162-postValentineDay/00-collection_updateSale.sql new file mode 100644 index 000000000..cce8f4ff5 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-collection_updateSale.sql @@ -0,0 +1,42 @@ +DROP procedure IF EXISTS `vn`.`collection_updateSale`; + + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`collection_updateSale`( + vSaleFk INT, + vOriginalQuantity INT, + vWorkerFk INT, + vStateFk INT, + vTicketFk INT) +BEGIN + + DECLARE vNumPrepared INT; + DECLARE vNumTotal INT; + + REPLACE INTO vn.saleTracking(saleFk,isChecked, originalQuantity, workerFk, actionFk,stateFk) + VALUES(vSaleFk,1,vOriginalQuantity,vWorkerFk,vStateFk,vStateFk); + + UPDATE vn.sale SET isPicked = 1 + WHERE id = vSaleFk; + + SELECT COUNT(s.id) INTO vNumPrepared + FROM vn.sale s + WHERE s.ticketFk = vTicketFk AND s.isPicked = 1; + + SELECT COUNT(s.id) INTO vNumTotal + FROM vn.sale s + WHERE s.ticketFk = vTicketFk; + + IF vNumPrepared = vNumTotal THEN + + INSERT INTO vncontrol.inter + SET state_id = vStateFk, Id_Ticket = vTicketFk, Id_Trabajador = vWorkerFk; + + CALL vn.collection_update(vTicketFk); + + END IF; + + +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-coolerPathDetail.sql b/db/changes/10162-postValentineDay/00-coolerPathDetail.sql new file mode 100644 index 000000000..7d3006544 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-coolerPathDetail.sql @@ -0,0 +1,13 @@ +/*DROP view IF EXISTS `vn`.`coolerPathDetail`; + +CREATE + ALGORITHM = UNDEFINED + DEFINER = `root`@`%` + SQL SECURITY DEFINER +VIEW `vn`.`coolerPathDetail` AS + SELECT + `c`.`cooler_path_detail_id` AS `id`, + `c`.`cooler_path_id` AS `coolerPathFk`, + `c`.`pasillo` AS `hallway` + FROM + `vn2008`.`cooler_path_detail` `c`*/ \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql b/db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql new file mode 100644 index 000000000..debdd3ac2 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql @@ -0,0 +1,15 @@ +DROP procedure IF EXISTS `vn`.`sale_updateOriginalQuantity`; + +DELIMITER $$ + +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`sale_updateOriginalQuantity`(vSale INT, vQuantity INT) +proc: BEGIN + +UPDATE vn.sale SET originalQuantity = vQuantity +WHERE id = vSale; + +SELECT * FROM vn.sale WHERE id = vSale; + +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-sector_getWarehouse.sql b/db/changes/10162-postValentineDay/00-sector_getWarehouse.sql new file mode 100644 index 000000000..90611b559 --- /dev/null +++ b/db/changes/10162-postValentineDay/00-sector_getWarehouse.sql @@ -0,0 +1,14 @@ +DROP procedure IF EXISTS `vn`.`sector_getWarehouse`; + +DELIMITER $$ + +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`sector_getWarehouse`(vSectorFk INT) +BEGIN + + SELECT s.warehouseFk + FROM vn.sector s + WHERE s.id = vSectorFk; + +END$$ + +DELIMITER ; \ No newline at end of file From 1c757a11047fb4aa24a62ff859acb4de12d8f1c8 Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Mon, 16 Mar 2020 10:25:49 +0100 Subject: [PATCH 17/25] structure DB --- db/dump/dumpedFixtures.sql | 30 +- db/dump/structure.sql | 3450 +++++++++++++++++++++++++++++------- 2 files changed, 2828 insertions(+), 652 deletions(-) diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index acdd3ea14..2f2f826a1 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -23,7 +23,7 @@ USE `util`; LOCK TABLES `config` WRITE; /*!40000 ALTER TABLE `config` DISABLE KEYS */; -INSERT INTO `config` VALUES (1,'10160',0,'production',NULL); +INSERT INTO `config` VALUES (1,'10161',0,'production',NULL); /*!40000 ALTER TABLE `config` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -36,7 +36,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-02-27 13:26:24 +-- Dump completed on 2020-03-16 9:45:09 USE `account`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -61,7 +61,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (0,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2018-04-23 14:33:59'),(1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31'),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35'),(13,'teamBoss','Jefe de departamento',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10'),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27'),(20,'manager','Departamento de gerencia',1,'2017-06-01 14:57:02','2017-06-01 14:57:51'),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52'),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12'),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36'),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27'),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20'),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34'),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53'),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42'),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08'),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53'),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09'),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41'),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12'),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26'),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59'),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16'),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12'),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23'),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18'),(48,'coolerBoss','Jefe del departamento de cámara',1,'2018-02-23 13:12:01','2018-02-23 13:12:01'),(49,'production','Empleado de producción',0,'2018-02-26 15:28:23','2019-01-21 12:57:21'),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12'),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39'),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57'),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57'),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17'),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31'),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02'),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19'),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45'),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10'),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01'),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07'),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05'),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08'),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26'),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56'),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23'),(69,'coolerAssist','Empleado cámara con permiso compras',1,'2020-02-05 12:36:09','2020-02-05 12:36:09'); +INSERT INTO `role` VALUES (0,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2018-04-23 14:33:59'),(1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31'),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35'),(13,'teamBoss','Jefe de departamento',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10'),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27'),(20,'manager','Departamento de gerencia',1,'2017-06-01 14:57:02','2017-06-01 14:57:51'),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52'),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12'),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36'),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27'),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20'),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34'),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53'),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42'),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08'),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53'),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09'),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41'),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12'),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26'),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59'),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16'),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12'),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23'),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18'),(48,'coolerBoss','Jefe del departamento de cámara',1,'2018-02-23 13:12:01','2018-02-23 13:12:01'),(49,'production','Empleado de producción',0,'2018-02-26 15:28:23','2019-01-21 12:57:21'),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12'),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39'),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57'),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57'),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17'),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31'),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02'),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19'),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45'),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10'),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01'),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07'),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05'),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08'),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26'),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56'),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23'),(69,'coolerAssist','Empleado cámara con permiso compras',1,'2020-02-05 12:36:09','2020-02-05 12:36:09'),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25'); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -71,7 +71,7 @@ UNLOCK TABLES; LOCK TABLES `roleInherit` WRITE; /*!40000 ALTER TABLE `roleInherit` DISABLE KEYS */; -INSERT INTO `roleInherit` VALUES (9,0),(66,0),(5,1),(13,1),(18,1),(31,1),(32,1),(34,1),(35,1),(37,1),(40,1),(42,1),(44,1),(47,1),(51,1),(53,1),(54,1),(56,1),(58,1),(1,2),(1,3),(30,5),(39,5),(60,5),(67,5),(11,6),(1,11),(2,11),(3,11),(16,13),(20,13),(21,13),(22,13),(34,13),(41,13),(43,13),(45,13),(48,13),(50,13),(52,13),(55,13),(57,13),(59,13),(61,13),(16,15),(20,16),(21,18),(52,19),(65,19),(17,20),(30,20),(5,21),(19,21),(22,21),(39,21),(50,21),(30,22),(5,33),(34,33),(15,35),(41,35),(50,35),(52,35),(65,35),(69,35),(49,36),(61,36),(17,37),(38,37),(60,37),(67,37),(17,39),(41,40),(43,42),(36,44),(45,44),(36,47),(48,47),(69,47),(50,49),(60,50),(65,50),(52,51),(21,53),(30,53),(55,54),(57,56),(15,57),(39,57),(50,57),(60,57),(49,58),(59,58),(50,59),(17,64),(30,64),(38,64),(20,65); +INSERT INTO `roleInherit` VALUES (9,0),(66,0),(5,1),(13,1),(18,1),(31,1),(32,1),(34,1),(35,1),(37,1),(40,1),(42,1),(44,1),(47,1),(51,1),(53,1),(54,1),(56,1),(58,1),(1,2),(1,3),(30,5),(39,5),(60,5),(67,5),(11,6),(2,11),(3,11),(70,11),(16,13),(20,13),(21,13),(22,13),(34,13),(41,13),(43,13),(45,13),(48,13),(50,13),(52,13),(55,13),(57,13),(59,13),(61,13),(16,15),(20,16),(21,18),(52,19),(65,19),(17,20),(30,20),(5,21),(19,21),(22,21),(39,21),(50,21),(30,22),(5,33),(34,33),(15,35),(41,35),(50,35),(52,35),(65,35),(69,35),(49,36),(61,36),(17,37),(38,37),(60,37),(67,37),(17,39),(41,40),(43,42),(36,44),(45,44),(36,47),(48,47),(69,47),(50,49),(60,50),(65,50),(52,51),(21,53),(30,53),(55,54),(57,56),(15,57),(39,57),(50,57),(60,57),(49,58),(59,58),(50,59),(17,64),(30,64),(38,64),(20,65),(1,70); /*!40000 ALTER TABLE `roleInherit` ENABLE KEYS */; UNLOCK TABLES; @@ -81,7 +81,7 @@ UNLOCK TABLES; LOCK TABLES `roleRole` WRITE; /*!40000 ALTER TABLE `roleRole` DISABLE KEYS */; -INSERT INTO `roleRole` VALUES (0,0),(0,1),(0,2),(0,3),(0,5),(0,6),(0,9),(0,11),(0,13),(0,15),(0,16),(0,17),(0,18),(0,19),(0,20),(0,21),(0,22),(0,30),(0,31),(0,32),(0,33),(0,34),(0,35),(0,36),(0,37),(0,38),(0,39),(0,40),(0,41),(0,42),(0,43),(0,44),(0,45),(0,47),(0,48),(0,49),(0,50),(0,51),(0,52),(0,53),(0,54),(0,55),(0,56),(0,57),(0,58),(0,59),(0,60),(0,61),(0,62),(0,64),(0,65),(0,66),(0,67),(0,69),(1,1),(1,2),(1,3),(1,6),(1,11),(2,2),(2,6),(2,11),(3,3),(3,6),(3,11),(5,1),(5,2),(5,3),(5,5),(5,6),(5,11),(5,13),(5,18),(5,21),(5,33),(5,53),(6,6),(9,0),(9,1),(9,2),(9,3),(9,5),(9,6),(9,9),(9,11),(9,13),(9,15),(9,16),(9,17),(9,18),(9,19),(9,20),(9,21),(9,22),(9,30),(9,31),(9,32),(9,33),(9,34),(9,35),(9,36),(9,37),(9,38),(9,39),(9,40),(9,41),(9,42),(9,43),(9,44),(9,45),(9,47),(9,48),(9,49),(9,50),(9,51),(9,52),(9,53),(9,54),(9,55),(9,56),(9,57),(9,58),(9,59),(9,60),(9,61),(9,62),(9,64),(9,65),(9,66),(9,67),(9,69),(11,6),(11,11),(13,1),(13,2),(13,3),(13,6),(13,11),(13,13),(15,1),(15,2),(15,3),(15,6),(15,11),(15,13),(15,15),(15,35),(15,56),(15,57),(16,1),(16,2),(16,3),(16,6),(16,11),(16,13),(16,15),(16,16),(16,35),(16,56),(16,57),(17,1),(17,2),(17,3),(17,5),(17,6),(17,11),(17,13),(17,15),(17,16),(17,17),(17,18),(17,19),(17,20),(17,21),(17,33),(17,35),(17,36),(17,37),(17,39),(17,44),(17,47),(17,49),(17,50),(17,53),(17,56),(17,57),(17,58),(17,59),(17,64),(17,65),(18,1),(18,2),(18,3),(18,6),(18,11),(18,18),(19,1),(19,2),(19,3),(19,6),(19,11),(19,13),(19,18),(19,19),(19,21),(19,53),(20,1),(20,2),(20,3),(20,6),(20,11),(20,13),(20,15),(20,16),(20,18),(20,19),(20,20),(20,21),(20,35),(20,36),(20,44),(20,47),(20,49),(20,50),(20,53),(20,56),(20,57),(20,58),(20,59),(20,65),(21,1),(21,2),(21,3),(21,6),(21,11),(21,13),(21,18),(21,21),(21,53),(22,1),(22,2),(22,3),(22,6),(22,11),(22,13),(22,18),(22,21),(22,22),(22,53),(30,1),(30,2),(30,3),(30,5),(30,6),(30,11),(30,13),(30,15),(30,16),(30,18),(30,19),(30,20),(30,21),(30,22),(30,30),(30,33),(30,35),(30,36),(30,44),(30,47),(30,49),(30,50),(30,53),(30,56),(30,57),(30,58),(30,59),(30,64),(30,65),(31,1),(31,2),(31,3),(31,6),(31,11),(31,31),(32,1),(32,2),(32,3),(32,6),(32,11),(32,32),(33,33),(34,1),(34,2),(34,3),(34,6),(34,11),(34,13),(34,33),(34,34),(35,1),(35,2),(35,3),(35,6),(35,11),(35,35),(36,1),(36,2),(36,3),(36,6),(36,11),(36,36),(36,44),(36,47),(37,1),(37,2),(37,3),(37,6),(37,11),(37,37),(38,1),(38,2),(38,3),(38,6),(38,11),(38,37),(38,38),(38,64),(39,1),(39,2),(39,3),(39,5),(39,6),(39,11),(39,13),(39,18),(39,21),(39,33),(39,39),(39,53),(39,56),(39,57),(40,1),(40,2),(40,3),(40,6),(40,11),(40,40),(41,1),(41,2),(41,3),(41,6),(41,11),(41,13),(41,35),(41,40),(41,41),(42,1),(42,2),(42,3),(42,6),(42,11),(42,42),(43,1),(43,2),(43,3),(43,6),(43,11),(43,13),(43,42),(43,43),(44,1),(44,2),(44,3),(44,6),(44,11),(44,44),(45,1),(45,2),(45,3),(45,6),(45,11),(45,13),(45,44),(45,45),(47,1),(47,2),(47,3),(47,6),(47,11),(47,47),(48,1),(48,2),(48,3),(48,6),(48,11),(48,13),(48,47),(48,48),(49,1),(49,2),(49,3),(49,6),(49,11),(49,36),(49,44),(49,47),(49,49),(49,58),(50,1),(50,2),(50,3),(50,6),(50,11),(50,13),(50,18),(50,21),(50,35),(50,36),(50,44),(50,47),(50,49),(50,50),(50,53),(50,56),(50,57),(50,58),(50,59),(51,1),(51,2),(51,3),(51,6),(51,11),(51,51),(52,1),(52,2),(52,3),(52,6),(52,11),(52,13),(52,18),(52,19),(52,21),(52,35),(52,51),(52,52),(52,53),(53,1),(53,2),(53,3),(53,6),(53,11),(53,53),(54,1),(54,2),(54,3),(54,6),(54,11),(54,54),(55,1),(55,2),(55,3),(55,6),(55,11),(55,13),(55,54),(55,55),(56,1),(56,2),(56,3),(56,6),(56,11),(56,56),(57,1),(57,2),(57,3),(57,6),(57,11),(57,13),(57,56),(57,57),(58,1),(58,2),(58,3),(58,6),(58,11),(58,58),(59,1),(59,2),(59,3),(59,6),(59,11),(59,13),(59,58),(59,59),(60,1),(60,2),(60,3),(60,5),(60,6),(60,11),(60,13),(60,18),(60,21),(60,33),(60,35),(60,36),(60,37),(60,44),(60,47),(60,49),(60,50),(60,53),(60,56),(60,57),(60,58),(60,59),(60,60),(61,1),(61,2),(61,3),(61,6),(61,11),(61,13),(61,36),(61,44),(61,47),(61,61),(62,62),(64,64),(65,1),(65,2),(65,3),(65,6),(65,11),(65,13),(65,18),(65,19),(65,21),(65,35),(65,36),(65,44),(65,47),(65,49),(65,50),(65,53),(65,56),(65,57),(65,58),(65,59),(65,65),(66,0),(66,1),(66,2),(66,3),(66,5),(66,6),(66,9),(66,11),(66,13),(66,15),(66,16),(66,17),(66,18),(66,19),(66,20),(66,21),(66,22),(66,30),(66,31),(66,32),(66,33),(66,34),(66,35),(66,36),(66,37),(66,38),(66,39),(66,40),(66,41),(66,42),(66,43),(66,44),(66,45),(66,47),(66,48),(66,49),(66,50),(66,51),(66,52),(66,53),(66,54),(66,55),(66,56),(66,57),(66,58),(66,59),(66,60),(66,61),(66,62),(66,64),(66,65),(66,66),(66,67),(66,69),(67,1),(67,2),(67,3),(67,5),(67,6),(67,11),(67,13),(67,18),(67,21),(67,33),(67,37),(67,53),(67,67),(69,1),(69,2),(69,3),(69,6),(69,11),(69,35),(69,47),(69,69); +INSERT INTO `roleRole` VALUES (0,0),(0,1),(0,2),(0,3),(0,5),(0,6),(0,9),(0,11),(0,13),(0,15),(0,16),(0,17),(0,18),(0,19),(0,20),(0,21),(0,22),(0,30),(0,31),(0,32),(0,33),(0,34),(0,35),(0,36),(0,37),(0,38),(0,39),(0,40),(0,41),(0,42),(0,43),(0,44),(0,45),(0,47),(0,48),(0,49),(0,50),(0,51),(0,52),(0,53),(0,54),(0,55),(0,56),(0,57),(0,58),(0,59),(0,60),(0,61),(0,62),(0,64),(0,65),(0,66),(0,67),(0,69),(0,70),(1,1),(1,2),(1,3),(1,6),(1,11),(1,70),(2,2),(2,6),(2,11),(3,3),(3,6),(3,11),(5,1),(5,2),(5,3),(5,5),(5,6),(5,11),(5,13),(5,18),(5,21),(5,33),(5,53),(5,70),(6,6),(9,0),(9,1),(9,2),(9,3),(9,5),(9,6),(9,9),(9,11),(9,13),(9,15),(9,16),(9,17),(9,18),(9,19),(9,20),(9,21),(9,22),(9,30),(9,31),(9,32),(9,33),(9,34),(9,35),(9,36),(9,37),(9,38),(9,39),(9,40),(9,41),(9,42),(9,43),(9,44),(9,45),(9,47),(9,48),(9,49),(9,50),(9,51),(9,52),(9,53),(9,54),(9,55),(9,56),(9,57),(9,58),(9,59),(9,60),(9,61),(9,62),(9,64),(9,65),(9,66),(9,67),(9,69),(9,70),(11,6),(11,11),(13,1),(13,2),(13,3),(13,6),(13,11),(13,13),(13,70),(15,1),(15,2),(15,3),(15,6),(15,11),(15,13),(15,15),(15,35),(15,56),(15,57),(15,70),(16,1),(16,2),(16,3),(16,6),(16,11),(16,13),(16,15),(16,16),(16,35),(16,56),(16,57),(16,70),(17,1),(17,2),(17,3),(17,5),(17,6),(17,11),(17,13),(17,15),(17,16),(17,17),(17,18),(17,19),(17,20),(17,21),(17,33),(17,35),(17,36),(17,37),(17,39),(17,44),(17,47),(17,49),(17,50),(17,53),(17,56),(17,57),(17,58),(17,59),(17,64),(17,65),(17,70),(18,1),(18,2),(18,3),(18,6),(18,11),(18,18),(18,70),(19,1),(19,2),(19,3),(19,6),(19,11),(19,13),(19,18),(19,19),(19,21),(19,53),(19,70),(20,1),(20,2),(20,3),(20,6),(20,11),(20,13),(20,15),(20,16),(20,18),(20,19),(20,20),(20,21),(20,35),(20,36),(20,44),(20,47),(20,49),(20,50),(20,53),(20,56),(20,57),(20,58),(20,59),(20,65),(20,70),(21,1),(21,2),(21,3),(21,6),(21,11),(21,13),(21,18),(21,21),(21,53),(21,70),(22,1),(22,2),(22,3),(22,6),(22,11),(22,13),(22,18),(22,21),(22,22),(22,53),(22,70),(30,1),(30,2),(30,3),(30,5),(30,6),(30,11),(30,13),(30,15),(30,16),(30,18),(30,19),(30,20),(30,21),(30,22),(30,30),(30,33),(30,35),(30,36),(30,44),(30,47),(30,49),(30,50),(30,53),(30,56),(30,57),(30,58),(30,59),(30,64),(30,65),(30,70),(31,1),(31,2),(31,3),(31,6),(31,11),(31,31),(31,70),(32,1),(32,2),(32,3),(32,6),(32,11),(32,32),(32,70),(33,33),(34,1),(34,2),(34,3),(34,6),(34,11),(34,13),(34,33),(34,34),(34,70),(35,1),(35,2),(35,3),(35,6),(35,11),(35,35),(35,70),(36,1),(36,2),(36,3),(36,6),(36,11),(36,36),(36,44),(36,47),(36,70),(37,1),(37,2),(37,3),(37,6),(37,11),(37,37),(37,70),(38,1),(38,2),(38,3),(38,6),(38,11),(38,37),(38,38),(38,64),(38,70),(39,1),(39,2),(39,3),(39,5),(39,6),(39,11),(39,13),(39,18),(39,21),(39,33),(39,39),(39,53),(39,56),(39,57),(39,70),(40,1),(40,2),(40,3),(40,6),(40,11),(40,40),(40,70),(41,1),(41,2),(41,3),(41,6),(41,11),(41,13),(41,35),(41,40),(41,41),(41,70),(42,1),(42,2),(42,3),(42,6),(42,11),(42,42),(42,70),(43,1),(43,2),(43,3),(43,6),(43,11),(43,13),(43,42),(43,43),(43,70),(44,1),(44,2),(44,3),(44,6),(44,11),(44,44),(44,70),(45,1),(45,2),(45,3),(45,6),(45,11),(45,13),(45,44),(45,45),(45,70),(47,1),(47,2),(47,3),(47,6),(47,11),(47,47),(47,70),(48,1),(48,2),(48,3),(48,6),(48,11),(48,13),(48,47),(48,48),(48,70),(49,1),(49,2),(49,3),(49,6),(49,11),(49,36),(49,44),(49,47),(49,49),(49,58),(49,70),(50,1),(50,2),(50,3),(50,6),(50,11),(50,13),(50,18),(50,21),(50,35),(50,36),(50,44),(50,47),(50,49),(50,50),(50,53),(50,56),(50,57),(50,58),(50,59),(50,70),(51,1),(51,2),(51,3),(51,6),(51,11),(51,51),(51,70),(52,1),(52,2),(52,3),(52,6),(52,11),(52,13),(52,18),(52,19),(52,21),(52,35),(52,51),(52,52),(52,53),(52,70),(53,1),(53,2),(53,3),(53,6),(53,11),(53,53),(53,70),(54,1),(54,2),(54,3),(54,6),(54,11),(54,54),(54,70),(55,1),(55,2),(55,3),(55,6),(55,11),(55,13),(55,54),(55,55),(55,70),(56,1),(56,2),(56,3),(56,6),(56,11),(56,56),(56,70),(57,1),(57,2),(57,3),(57,6),(57,11),(57,13),(57,56),(57,57),(57,70),(58,1),(58,2),(58,3),(58,6),(58,11),(58,58),(58,70),(59,1),(59,2),(59,3),(59,6),(59,11),(59,13),(59,58),(59,59),(59,70),(60,1),(60,2),(60,3),(60,5),(60,6),(60,11),(60,13),(60,18),(60,21),(60,33),(60,35),(60,36),(60,37),(60,44),(60,47),(60,49),(60,50),(60,53),(60,56),(60,57),(60,58),(60,59),(60,60),(60,70),(61,1),(61,2),(61,3),(61,6),(61,11),(61,13),(61,36),(61,44),(61,47),(61,61),(61,70),(62,62),(64,64),(65,1),(65,2),(65,3),(65,6),(65,11),(65,13),(65,18),(65,19),(65,21),(65,35),(65,36),(65,44),(65,47),(65,49),(65,50),(65,53),(65,56),(65,57),(65,58),(65,59),(65,65),(65,70),(66,0),(66,1),(66,2),(66,3),(66,5),(66,6),(66,9),(66,11),(66,13),(66,15),(66,16),(66,17),(66,18),(66,19),(66,20),(66,21),(66,22),(66,30),(66,31),(66,32),(66,33),(66,34),(66,35),(66,36),(66,37),(66,38),(66,39),(66,40),(66,41),(66,42),(66,43),(66,44),(66,45),(66,47),(66,48),(66,49),(66,50),(66,51),(66,52),(66,53),(66,54),(66,55),(66,56),(66,57),(66,58),(66,59),(66,60),(66,61),(66,62),(66,64),(66,65),(66,66),(66,67),(66,69),(66,70),(67,1),(67,2),(67,3),(67,5),(67,6),(67,11),(67,13),(67,18),(67,21),(67,33),(67,37),(67,53),(67,67),(67,70),(69,1),(69,2),(69,3),(69,6),(69,11),(69,35),(69,47),(69,69),(69,70),(70,6),(70,11),(70,70); /*!40000 ALTER TABLE `roleRole` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -94,7 +94,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-02-27 13:26:25 +-- Dump completed on 2020-03-16 9:45:11 USE `salix`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -119,7 +119,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','employee'),(111,'ClientLog','*','READ','ALLOW','ROLE','employee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','employee'),(114,'Receipt','*','READ','ALLOW','ROLE','employee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','employee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','employee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','salesAssistant'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','*','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(217,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','salesAssistant'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','*','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(219,'Account','acl','READ','ALLOW','ROLE','account'),(220,'Account','getCurrentUserData','READ','ALLOW','ROLE','account'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(229,'CustomsAgent','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; @@ -142,7 +142,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-02-27 13:26:25 +-- Dump completed on 2020-03-16 9:45:12 USE `vn`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -287,7 +287,7 @@ UNLOCK TABLES; LOCK TABLES `state` WRITE; /*!40000 ALTER TABLE `state` DISABLE KEYS */; -INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0,0,0),(2,'Libre',2,0,'FREE',NULL,2,0,0,0,0,1),(3,'OK',3,0,'OK',3,28,1,0,0,0,1),(4,'Impreso',4,1,'PRINTED',2,29,1,0,1,0,0),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0,0,2,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0,3,0),(7,'Sin Acabar',1,0,'NOT_READY',NULL,7,0,0,0,0,1),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0,3,0),(9,'Encajando',9,2,'PACKING',NULL,9,0,1,0,0,0),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0,0,0),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1,0,0,0),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0,0,0),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0,0,0),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0,2,0),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0,0,0),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0,0,0),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0,0,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0,0,0,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0,0,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0,0,0,0),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0,0,0,0),(24,'Encadenado',4,0,'CHAINED',4,24,0,0,0,0,0),(25,'Embarcando',3,0,'BOARDING',5,25,0,0,0,0,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0,0,1,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0,0,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0,0,1,1),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0,1,1,0),(30,'Embarcado',4,0,'BOARD',5,30,0,0,0,2,0); +INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0,0,0,0),(2,'Libre',2,0,'FREE',NULL,2,0,0,0,0,1,0),(3,'OK',3,0,'OK',3,28,1,0,0,0,1,1),(4,'Impreso',4,1,'PRINTED',2,29,1,0,1,0,0,0),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0,0,2,0,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0,3,0,0),(7,'Sin Acabar',1,0,'NOT_READY',NULL,7,0,0,0,0,1,0),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0,3,0,0),(9,'Encajando',9,2,'PACKING',NULL,9,0,1,0,0,0,0),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0,0,0,0),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1,0,0,0,0),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0,0,0,0),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0,0,0,0),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0,2,0,0),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0,0,0,0),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0,0,0,0),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0,0,0,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0,0,0,0,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0,0,0,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0,0,0,0,0),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0,0,0,0,0),(24,'Encadenado',4,0,'CHAINED',4,24,0,0,0,0,0,0),(25,'Embarcando',3,0,'BOARDING',5,25,0,0,0,0,0,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0,0,1,0,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0,0,0,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0,0,1,1,1),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0,1,1,0,0),(30,'Embarcado',4,0,'BOARD',5,30,0,0,0,2,0,0); /*!40000 ALTER TABLE `state` ENABLE KEYS */; UNLOCK TABLES; @@ -307,7 +307,7 @@ UNLOCK TABLES; LOCK TABLES `department` WRITE; /*!40000 ALTER TABLE `department` DISABLE KEYS */; -INSERT INTO `department` VALUES (1,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(22,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/',NULL),(23,'CAMARA',5,6,NULL,72,604,2,6,1,0,0,0,NULL,'/',NULL),(31,'INFORMATICA',7,8,NULL,72,127,3,9,0,0,0,0,NULL,'/','informatica'),(34,'CONTABILIDAD',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(35,'FINANZAS',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(36,'LABORAL',13,14,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(37,'PRODUCCION',15,42,NULL,72,230,3,11,0,0,0,13,NULL,'/',NULL),(38,'SACADO',16,17,NULL,72,230,4,14,1,0,1,0,37,'/37/',NULL),(39,'ENCAJADO',18,19,NULL,72,230,4,12,1,0,1,0,37,'/37/',NULL),(41,'ADMINISTRACION',43,44,NULL,72,599,3,8,0,0,0,0,NULL,'/',NULL),(43,'VENTAS',45,66,NULL,0,NULL,NULL,NULL,0,0,0,10,NULL,'/',NULL),(44,'GERENCIA',67,68,NULL,72,300,2,7,0,0,0,0,NULL,'/',NULL),(45,'LOGISTICA',69,70,NULL,72,596,3,19,0,0,0,0,NULL,'/',NULL),(46,'REPARTO',20,21,NULL,72,659,3,10,0,0,1,0,37,'/37/',NULL),(48,'ALMACENAJE',71,72,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(49,'PROPIEDAD',73,74,NULL,72,1008,1,1,0,0,0,0,NULL,'/',NULL),(52,'CARGA AEREA',75,76,NULL,72,163,4,28,0,0,0,0,NULL,'/',NULL),(53,'MARKETING Y COMUNICACIÓN',77,78,NULL,72,1238,0,0,0,0,0,0,NULL,'/',NULL),(54,'ORNAMENTALES',79,80,NULL,72,433,3,21,0,0,0,0,NULL,'/',NULL),(55,'TALLER NATURAL',81,82,NULL,72,695,2,23,0,0,0,0,NULL,'/',NULL),(56,'TALLER ARTIFICIAL',83,84,NULL,72,1780,2,24,0,0,0,0,NULL,'/',NULL),(58,'CAMPOS',85,86,NULL,72,225,2,2,0,0,0,0,NULL,'/',NULL),(59,'MANTENIMIENTO',87,88,NULL,72,1907,4,16,0,0,0,0,NULL,'/',NULL),(60,'RECLAMACIONES',89,90,NULL,72,563,3,20,0,0,0,0,NULL,'/',NULL),(61,'VNH',91,92,NULL,73,1297,3,17,0,0,0,0,NULL,'/',NULL),(63,'VENTAS FRANCIA',46,47,NULL,72,277,2,27,0,0,1,0,43,'/43/',NULL),(66,'VERDNAMADRID',93,94,NULL,72,163,3,18,0,0,0,0,NULL,'/',NULL),(68,'COMPLEMENTOS',95,96,NULL,72,617,3,26,1,0,0,0,NULL,'/',NULL),(69,'VERDNABARNA',97,98,NULL,74,432,3,22,0,0,0,0,NULL,'/',NULL),(77,'PALETIZADO',22,23,NULL,72,230,4,15,1,0,1,0,37,'/37/',NULL),(80,'EQUIPO J VALLES',48,49,NULL,72,693,3,4,0,0,1,0,43,'/43/','jvp_equipo'),(86,'LIMPIEZA',99,100,NULL,72,599,0,0,0,0,0,0,NULL,'/',NULL),(89,'COORDINACION',101,102,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/',NULL),(90,'TRAILER',103,104,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(91,'ARTIFICIAL',105,106,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/',NULL),(92,'EQUIPO SILVERIO',50,51,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','sdc_equipo'),(93,'CONFECCION',107,108,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(94,'EQUIPO J BROCAL',52,53,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jes_equipo'),(95,'EQUIPO C ZAMBRANO',54,55,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','czg_equipo'),(96,'EQUIPO C LOPEZ',56,57,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','cla_equipo'),(97,'EQUIPO D SARRION',58,59,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','dsr_equipo'),(98,'EQUIPO RODRIGO',60,61,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','rhr_equipo'),(99,'EQUIPO MANOLI',62,63,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','man_equipo'),(101,'EQUIPO J IBAÑEZ',64,65,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jmi_equipo'),(102,'EQ ROJO FV RUBEN C',24,25,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL),(103,'EQ AZUL FV A FOLQUES',26,27,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL),(104,'EQ AMARILLO FV NORMAN G',28,29,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL),(105,'EQ MORADO FV MATOU',30,31,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL),(106,'EQ VERDE PCA KEVIN GIMENEZ',32,33,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL),(107,'EQ NARANJA PCA RUBEN ZANON',34,35,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL),(109,'EQ MARRON PCA JC ESTELLES',36,37,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL),(110,'EQ ROSA PCA J BONDIA',38,39,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL),(111,'EQ REPONEDOR CAJAS',40,41,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL); +INSERT INTO `department` VALUES (1,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(22,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/',NULL),(23,'CAMARA',14,19,NULL,72,604,2,6,1,0,1,2,37,'/37/',NULL),(31,'INFORMATICA',5,6,NULL,72,127,3,9,0,0,0,0,NULL,'/','informatica'),(34,'CONTABILIDAD',7,8,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(35,'FINANZAS',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(36,'LABORAL',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(37,'PRODUCCION',13,46,NULL,72,230,3,11,1,0,0,14,NULL,'/',NULL),(38,'SACADO',20,21,NULL,72,230,4,14,1,0,1,0,37,'/37/',NULL),(39,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,1,0,37,'/37/',NULL),(41,'ADMINISTRACION',47,48,NULL,72,599,3,8,0,0,0,0,NULL,'/',NULL),(43,'VENTAS',49,70,NULL,0,NULL,NULL,NULL,0,0,0,10,NULL,'/',NULL),(44,'GERENCIA',71,72,NULL,72,300,2,7,0,0,0,0,NULL,'/',NULL),(45,'LOGISTICA',73,74,NULL,72,596,3,19,0,0,0,0,NULL,'/',NULL),(46,'REPARTO',75,78,NULL,72,659,3,10,0,0,0,1,NULL,'/',NULL),(48,'ALMACENAJE',79,80,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(49,'PROPIEDAD',81,82,NULL,72,1008,1,1,0,0,0,0,NULL,'/',NULL),(52,'CARGA AEREA',83,84,NULL,72,163,4,28,0,0,0,0,NULL,'/',NULL),(53,'MARKETING Y COMUNICACIÓN',85,86,NULL,72,1238,0,0,0,0,0,0,NULL,'/',NULL),(54,'ORNAMENTALES',87,88,NULL,72,433,3,21,0,0,0,0,NULL,'/',NULL),(55,'TALLER NATURAL',89,90,NULL,72,695,2,23,0,0,0,0,NULL,'/',NULL),(56,'TALLER ARTIFICIAL',91,92,NULL,72,1780,2,24,0,0,0,0,NULL,'/',NULL),(58,'CAMPOS',93,94,NULL,72,225,2,2,0,0,0,0,NULL,'/',NULL),(59,'MANTENIMIENTO',95,96,NULL,72,1907,4,16,0,0,0,0,NULL,'/',NULL),(60,'RECLAMACIONES',97,98,NULL,72,563,3,20,0,0,0,0,NULL,'/',NULL),(61,'VNH',99,100,NULL,73,1297,3,17,0,0,0,0,NULL,'/',NULL),(63,'VENTAS FRANCIA',50,51,NULL,72,277,2,27,0,0,1,0,43,'/43/',NULL),(66,'VERDNAMADRID',101,102,NULL,72,163,3,18,0,0,0,0,NULL,'/',NULL),(68,'COMPLEMENTOS',24,25,NULL,72,617,3,26,1,0,1,0,37,'/37/',NULL),(69,'VERDNABARNA',103,104,NULL,74,432,3,22,0,0,0,0,NULL,'/',NULL),(77,'PALETIZADO',76,77,NULL,72,230,4,15,0,0,1,0,46,'/46/',NULL),(80,'EQUIPO J VALLES',52,53,NULL,72,693,3,4,0,0,1,0,43,'/43/','jvp_equipo'),(86,'LIMPIEZA',105,106,NULL,72,599,0,0,0,0,0,0,NULL,'/',NULL),(89,'COORDINACION',107,108,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(90,'TRAILER',109,110,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(91,'ARTIFICIAL',26,27,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(92,'EQUIPO SILVERIO',54,55,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','sdc_equipo'),(93,'CONFECCION',111,112,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(94,'EQUIPO J BROCAL',56,57,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jes_equipo'),(95,'EQUIPO C ZAMBRANO',58,59,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','czg_equipo'),(96,'EQUIPO C LOPEZ',60,61,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','cla_equipo'),(97,'EQUIPO D SARRION',62,63,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','dsr_equipo'),(98,'EQUIPO RODRIGO',64,65,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','rhr_equipo'),(99,'EQUIPO MANOLI',66,67,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','man_equipo'),(101,'EQUIPO J IBAÑEZ',68,69,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jmi_equipo'),(102,'EQ ROJO FV RUBEN C',28,29,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(103,'EQ AZUL FV A FOLQUES',30,31,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(104,'EQ AMARILLO FV NORMAN G',32,33,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(105,'EQ MORADO FV MATOU',34,35,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(106,'EQ VERDE PCA KEVIN GIMENEZ',36,37,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(107,'EQ NARANJA PCA RUBEN ZANON',38,39,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(110,'EQ ROSA PCA J BONDIA',40,41,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(111,'EQ REPONEDOR CAJAS',42,43,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(112,'CAMARA EQ EDGAR LLEO',15,16,NULL,0,NULL,NULL,NULL,0,0,2,0,23,'/37/23/',NULL),(113,'CAMARA EQ MARC ROCA',17,18,NULL,0,NULL,NULL,NULL,0,0,2,0,23,'/37/23/',NULL),(114,'EQ MARRON PCA JL NUEVO',44,45,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL); /*!40000 ALTER TABLE `department` ENABLE KEYS */; UNLOCK TABLES; @@ -340,7 +340,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-02-27 13:26:25 +-- Dump completed on 2020-03-16 9:45:18 USE `cache`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -378,7 +378,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-02-27 13:26:26 +-- Dump completed on 2020-03-16 9:45:19 USE `hedera`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -436,7 +436,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-02-27 13:26:26 +-- Dump completed on 2020-03-16 9:45:21 USE `postgresql`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -511,7 +511,7 @@ UNLOCK TABLES; LOCK TABLES `workcenter` WRITE; /*!40000 ALTER TABLE `workcenter` DISABLE KEYS */; -INSERT INTO `workcenter` VALUES (1,'Silla',20,1030,1),(2,'Mercaflor',19,NULL,NULL),(3,'Marjales',26,20008,NULL),(4,'VNH',NULL,NULL,3),(5,'Madrid',28,2852,5),(6,'Vilassar',88,88031,2),(7,'Tenerife',NULL,NULL,10); +INSERT INTO `workcenter` VALUES (1,'Silla',20,1033,1),(2,'Mercaflor',19,NULL,NULL),(3,'Marjales',26,20008,NULL),(4,'VNH',NULL,NULL,3),(5,'Madrid',28,2852,5),(6,'Vilassar',88,88031,2),(7,'Tenerife',NULL,NULL,10); /*!40000 ALTER TABLE `workcenter` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -524,4 +524,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-02-27 13:26:27 +-- Dump completed on 2020-03-16 9:45:23 diff --git a/db/dump/structure.sql b/db/dump/structure.sql index c008cb055..8e783c833 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -2378,13 +2378,49 @@ CREATE TABLE `payMethodClientEvolution` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `productivity` +-- Table structure for table `produccion` -- -DROP TABLE IF EXISTS `productivity`; +DROP TABLE IF EXISTS `produccion`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivity` ( +CREATE TABLE `produccion` ( + `dated` date NOT NULL, + `m3` int(11) NOT NULL DEFAULT '0', + `cost` int(11) NOT NULL DEFAULT '0', + `eurosM3` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`dated`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `productivityDepartment__` +-- + +DROP TABLE IF EXISTS `productivityDepartment__`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `productivityDepartment__` ( + `dated` date NOT NULL, + `amountCoordinacion` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountSacado` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountEncajado` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountPaletizado` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountCamara` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountComplementos` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountArtificial` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`dated`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `productivity__` +-- + +DROP TABLE IF EXISTS `productivity__`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `productivity__` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `dated` date NOT NULL, `hh` int(10) unsigned NOT NULL, @@ -2414,33 +2450,13 @@ CREATE TABLE `productivity` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `productivityDepartment` +-- Table structure for table `productivity_evolution__` -- -DROP TABLE IF EXISTS `productivityDepartment`; +DROP TABLE IF EXISTS `productivity_evolution__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivityDepartment` ( - `dated` date NOT NULL, - `amountCoordinacion` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountSacado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountEncajado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountPaletizado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountCamara` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountComplementos` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountArtificial` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`dated`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `productivity_evolution` --- - -DROP TABLE IF EXISTS `productivity_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivity_evolution` ( +CREATE TABLE `productivity_evolution__` ( `dated` date NOT NULL, `m3productionCost` decimal(10,2) NOT NULL DEFAULT '0.00', PRIMARY KEY (`dated`) @@ -3104,116 +3120,142 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `comercialesCompleto`(IN vWorker INT, vDate DATE) BEGIN - -CALL vn.worker_GetHierarchy(vWorker); - -SELECT - c.Id_Cliente id_cliente, - c.calidad, - c.Cliente cliente, - cr.recobro * 100 tarifa, - c.Telefono telefono, - c.movil, - c.POBLACION poblacion, - p.`name` provincia, - vn2008.red(f.futur) futur, - c.Credito credito, - pm.`name` forma_pago, - vn2008.red(c365 / 12) consumo_medio365, - vn2008.red(c365) consumo365, - vn2008.red(CmLy.peso) peso_mes_año_pasado, - vn2008.red(CmLy.peso * 1.19) objetivo, - tr.CodigoTrabajador, - vn2008.red(mes_actual.consumo) consumoMes, - vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo, - DATE(LastTicket) ultimo_ticket, - dead.muerto, - g.Greuge, - cr.recobro -FROM - vn2008.Clientes c - LEFT JOIN - (SELECT Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge - FROM vn2008.Greuges - GROUP BY Id_Cliente - ) g ON g.Id_Cliente = c.Id_Cliente - LEFT JOIN - vn2008.province p ON p.province_id = c.province_id - JOIN - vn2008.pay_met pm ON pm.id = c.pay_met_id - LEFT JOIN - vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - LEFT JOIN - bi.claims_ratio cr on cr.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT v.Id_Cliente, SUM(importe) c365 -- optimizat de 6s /5.3s/ 4.7s a 0.3/0.4/0.3 - FROM bs.ventas v - JOIN vn2008.Clientes c USING (Id_Cliente) + CALL vn.worker_GetHierarchy(vWorker); + + INSERT IGNORE INTO tmp.workerHierarchyList (workerFk) + SELECT wd2.workerFk + FROM vn.departmentItemType dit + JOIN vn.workerDepartment wd2 ON wd2.departmentFk = dit.departmentFk + WHERE dit.workerFk = vWorker; + + DROP TABLE IF EXISTS tmp.itemTypeExcluded; + CREATE TABLE tmp.itemTypeExcluded + (itemTypeFk INT PRIMARY KEY) + ENGINE = MEMORY; + + IF (SELECT COUNT(*) FROM vn.departmentItemType WHERE workerFk = vWorker LIMIT 1) = 0 THEN + INSERT INTO tmp.itemTypeExcluded (itemTypeFk) + SELECT dit2.itemTypeFk + FROM vn.workerDepartment wd + JOIN vn.departmentItemType dit1 ON wd.departmentFk = dit1.departmentFk AND wd.workerFk = vWorker + JOIN vn.itemType it ON TRUE + LEFT JOIN vn.departmentItemType dit2 ON dit2.departmentFk = dit1.departmentFk AND dit2.itemTypeFk = it.id + WHERE dit2.itemTypeFk IS NOT NULL + GROUP BY it.id; + ELSE -- comercial especialista + INSERT INTO tmp.itemTypeExcluded (itemTypeFk) + SELECT it.id itemTypeFk + FROM vn.itemType it + JOIN vn.workerDepartment wd ON wd.workerFk = vWorker + LEFT JOIN vn.departmentItemType dit ON dit.itemTypeFk = it.id + WHERE NOT (dit.workerFk <=> vWorker); + END IF; + + -- Falta que en algunos casos solo tenga en cuenta los tipos afectados. + SELECT + c.Id_Cliente id_cliente, + c.calidad, + c.Cliente cliente, + cr.recobro * 100 tarifa, + c.Telefono telefono, + c.movil, + c.POBLACION poblacion, + p.`name` provincia, + vn2008.red(f.futur) futur, + c.Credito credito, + pm.`name` forma_pago, + vn2008.red(c365 / 12) consumo_medio365, + vn2008.red(c365) consumo365, + vn2008.red(CmLy.peso) peso_mes_año_pasado, + vn2008.red(CmLy.peso * 1.19) objetivo, + tr.CodigoTrabajador, + vn2008.red(mes_actual.consumo) consumoMes, + vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo, + DATE(LastTicket) ultimo_ticket, + dead.muerto, + g.Greuge, + cr.recobro + FROM + vn2008.Clientes c + LEFT JOIN + (SELECT Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge + FROM vn2008.Greuges + GROUP BY Id_Cliente + ) g ON g.Id_Cliente = c.Id_Cliente + LEFT JOIN + vn2008.province p ON p.province_id = c.province_id + JOIN + vn2008.pay_met pm ON pm.id = c.pay_met_id + LEFT JOIN + vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + LEFT JOIN + bi.claims_ratio cr on cr.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT v.Id_Cliente, SUM(importe) c365 -- optimizat de 6s /5.3s/ 4.7s a 0.3/0.4/0.3 + FROM bs.ventas v + JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente + LEFT JOIN tmp.itemTypeExcluded ite ON ite.itemTypeFk = v.tipo_id + WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate + AND ite.itemTypeFk IS NULL + GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT + Id_Cliente, SUM(importe) consumo + FROM + bs.ventas v + INNER JOIN vn2008.Clientes c USING (Id_Cliente) + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + LEFT JOIN tmp.itemTypeExcluded ite ON ite.itemTypeFk = v.tipo_id + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) AND ite.itemTypeFk IS NULL + AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate)) + GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT + t.Id_Cliente, + SUM(m.preu * m.Cantidad * (1 - m.Descuento / 100)) futur + FROM vn2008.Tickets t + JOIN vn2008.Clientes c ON c.Id_Cliente = t.Id_Cliente + JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + AND DATE(Fecha) BETWEEN vDate AND LAST_DAY(vDate) + GROUP BY Id_Cliente) f ON c.Id_Cliente = f.Id_Cliente + LEFT JOIN + (SELECT + MAX(t.Fecha) LastTicket, c.Id_Cliente + FROM + vn2008.Tickets t + JOIN vn2008.Clientes c ON c.Id_cliente = t.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate - GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - Id_Cliente, SUM(importe) consumo - FROM - bs.ventas v - INNER JOIN vn2008.Clientes c USING (Id_Cliente) - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate)) - GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - t.Id_Cliente, - SUM(m.preu * m.Cantidad * (1 - m.Descuento / 100)) futur - FROM - vn2008.Tickets t - JOIN vn2008.Clientes c ON c.Id_Cliente = t.Id_Cliente - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - AND DATE(Fecha) BETWEEN vDate AND LAST_DAY(vDate) - GROUP BY Id_Cliente) f ON c.Id_Cliente = f.Id_Cliente - LEFT JOIN - (SELECT - MAX(t.Fecha) LastTicket, c.Id_Cliente - FROM - vn2008.Tickets t - JOIN vn2008.Clientes c ON c.Id_cliente = t.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY t.Id_Cliente) LastTicket ON LastTicket.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - SUM(importe) peso, c.Id_Cliente - FROM - bs.ventas v - JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - MONTH(fecha) = MONTH(vDate) - AND YEAR(fecha) = YEAR(vDate) - 1 - AND (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - c.Id_Cliente, - IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto - FROM - vn2008.Facturas f - JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente - - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente - JOIN tmp.workerHierarchyList s ON s.workerFk = c.Id_Trabajador; + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + GROUP BY t.Id_Cliente) LastTicket ON LastTicket.Id_Cliente = c.Id_Cliente + LEFT JOIN + ( + SELECT SUM(importe) peso, c.Id_Cliente + FROM bs.ventas v + JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + LEFT JOIN tmp.itemTypeExcluded ite ON ite.itemTypeFk = v.tipo_id + WHERE MONTH(fecha) = MONTH(vDate) + AND YEAR(fecha) = YEAR(vDate) - 1 + AND (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT c.Id_Cliente, + IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto + FROM vn2008.Facturas f + JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + WHERE (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente + JOIN tmp.workerHierarchyList s ON s.workerFk = c.Id_Trabajador; -DROP TEMPORARY TABLE tmp.workerHierarchyList; + DROP TEMPORARY TABLE tmp.workerHierarchyList; + DROP TABLE IF EXISTS tmp.itemTypeExcluded; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4234,7 +4276,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityAdd` */; +/*!50003 DROP PROCEDURE IF EXISTS `produccionAdd` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -4244,7 +4286,127 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityAdd`(vDate DATE) +CREATE DEFINER=`root`@`%` PROCEDURE `produccionAdd`(vDate DATE) +BEGIN + + DECLARE vDateStart DATETIME DEFAULT vDate; + DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); + DECLARE myDepLft INT; + DECLARE myDepRgt INT; + + + -- Trabajadores + CALL vn.dayMinuteWorker(vDateStart,vDateEnd); -- Genera la tabla tmp.dayMinuteWorker + CALL vn.workerDepartmentByDate(vDate); + + -- General + REPLACE bs.produccion(dated, cost) + SELECT vDate,sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + WHERE Almacen IN (1,44) + AND wdd.isProduction; + + UPDATE bs.produccion p + JOIN (SELECT sum(volume) as m3 + FROM vn.saleVolume sv + JOIN vn.ticket t ON sv.ticketFk = t.id + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + WHERE t.shipped BETWEEN vDateStart AND vDateEnd + AND wa.name = 'Silla' + ) sub + SET p.m3 = sub.m3, + p.eurosM3 = p.cost / sub.m3 + WHERE p.dated = vDate; + + DROP TEMPORARY TABLE tmp.dayMinuteWorker; + DROP TEMPORARY TABLE tmp.workerDepartmentByDate; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `produccion_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `produccion_launcher`(vDateFrom DATE, vDateTo DATE) +BEGIN + + WHILE vDateFrom <= vDateTo DO + + CALL bs.produccionAdd(vDateFrom); + + SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `produccion_launcher_auto` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `produccion_launcher_auto`() +BEGIN + + DECLARE vDate DATE DEFAULT TIMESTAMPADD(WEEK, -1, CURDATE()); + + WHILE vDate <= CURDATE() DO + + CALL bs.produccionAdd(vDate); + + SET vDate = TIMESTAMPADD(DAY,1,vDate); + + END WHILE; + + SET vDate = TIMESTAMPADD(DAY,-372, CURDATE()); + + WHILE vDate <= TIMESTAMPADD(YEAR,-1, CURDATE()) DO + + CALL bs.produccionAdd(vDate); + + SET vDate = TIMESTAMPADD(DAY,1,vDate); + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityAdd__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityAdd__`(vDate DATE) BEGIN DECLARE vDateStart DATETIME DEFAULT vDate; @@ -4509,7 +4671,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentAdd` */; +/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentAdd__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -4519,7 +4681,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentAdd`(IN vDateStartPeriod DATETIME, IN vDateEndPeriod DATETIME, IN vDateStart DATETIME) +CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentAdd__`(IN vDateStartPeriod DATETIME, IN vDateEndPeriod DATETIME, IN vDateStart DATETIME) BEGIN DECLARE vEndingDate DATETIME; @@ -4572,17 +4734,17 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentLauncher` */; +/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentLauncher__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentLauncher`() +CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentLauncher__`() BEGIN CALL bs.productivityDepartmentAdd('2019-05-06', CURDATE(),DATE_SUB(CURDATE(), INTERVAL 2 WEEK)); END ;; @@ -4591,17 +4753,51 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher` */; +/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher_manual__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher`() +CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher_manual__`(vDateFrom DATE, vToDate DATE) +BEGIN + + TRUNCATE tmp.log; + + WHILE vToDate >= vDateFrom DO + + INSERT INTO tmp.log(text) VALUES (vDateFrom); + CALL bs.productivityAdd(vDateFrom); + + CALL bs.productivityAdd(TIMESTAMPADD(YEAR, -1,vDateFrom)); + INSERT INTO tmp.log(text) VALUES (TIMESTAMPADD(YEAR, -1,vDateFrom)); + + SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); + + END WHILE; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher__`() BEGIN DECLARE vDateFrom DATE; @@ -4622,40 +4818,6 @@ BEGIN SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); END WHILE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher_manual` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher_manual`(vDateFrom DATE, vToDate DATE) -BEGIN - - TRUNCATE tmp.log; - - WHILE vToDate >= vDateFrom DO - - INSERT INTO tmp.log(text) VALUES (vDateFrom); - CALL bs.productivityAdd(vDateFrom); - - CALL bs.productivityAdd(TIMESTAMPADD(YEAR, -1,vDateFrom)); - INSERT INTO tmp.log(text) VALUES (TIMESTAMPADD(YEAR, -1,vDateFrom)); - - SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); - - END WHILE; - - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -12009,13 +12171,13 @@ BEGIN SELECT COUNT(*) > 0 INTO vOk FROM order_row WHERE order_id = vOrder AND amount > 0; - IF !vOk THEN + IF NOT vOk THEN CALL util.throw ('ORDER_EMPTY'); END IF; -- Carga las fechas de salida de cada almacén - CALL vn.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId); + CALL vn.zone_getShipped (vDelivery, vAddress, vAgencyModeId, FALSE); -- Trabajador que realiza la acción @@ -12209,7 +12371,6 @@ BEGIN DECLARE vAgencyModeId INT; DECLARE TICKET_FREE INT DEFAULT 2; - DECLARE SYSTEM_WORKER INT DEFAULT 20; DECLARE cDates CURSOR FOR SELECT zgs.shipped, r.warehouse_id @@ -12220,9 +12381,9 @@ BEGIN GROUP BY r.warehouse_id; DECLARE cRows CURSOR FOR - SELECT r.id, r.item_id, a.Article, r.amount, r.price, r.rate + SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate FROM order_row r - JOIN vn2008.Articles a ON a.Id_Article = r.item_id + JOIN vn.item i ON i.id = r.item_id WHERE r.amount != 0 AND r.warehouse_id = vWarehouse AND r.order_id = vOrder @@ -12240,12 +12401,12 @@ BEGIN -- Carga los datos del pedido SELECT o.date_send, o.address_id, o.note, - o.confirmed, cs.Id_Cliente, o.company_id, o.agency_id + o.confirmed, a.clientFk, o.company_id, o.agency_id INTO vDelivery, vAddress, vNotes, vIsConfirmed, vClientId, vCompanyId, vAgencyModeId FROM hedera.`order` o - JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = o.address_id - WHERE id = vOrder; + JOIN vn.address a ON a.id = o.address_id + WHERE o.id = vOrder; -- Comprueba que el pedido no está confirmado @@ -12264,7 +12425,7 @@ BEGIN -- Carga las fechas de salida de cada almacén - CALL vn.zoneGetShippedWarehouse (vDelivery, vAddress, vAgencyModeId); + CALL vn.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId); -- Trabajador que realiza la acción @@ -12290,19 +12451,19 @@ BEGIN -- Busca un ticket existente que coincida con los parametros - SELECT Id_Ticket INTO vTicket - FROM vn2008.Tickets t - LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket + SELECT t.id INTO vTicket + FROM vn.ticket t + LEFT JOIN vn.ticketState tls on tls.ticket = t.id JOIN `order` o - ON o.address_id = t.Id_Consigna - AND vWarehouse = t.warehouse_id - AND o.agency_id = t.Id_Agencia - AND t.landing = o.date_send - AND vShipment = DATE(t.Fecha) + ON o.address_id = t.addressFk + AND vWarehouse = t.warehouseFk + AND o.agency_id = t.agencyModeFk + AND o.date_send = t.landed + AND vShipment = DATE(t.shipped) WHERE o.id = vOrder - AND t.Factura IS NULL + AND t.invoiceOutFk IS NULL AND IFNULL(tls.alertLevel,0) = 0 - AND t.Id_Cliente <> 1118 + AND t.clientFk <> 1118 LIMIT 1; -- Crea el ticket en el caso de no existir uno adecuado @@ -12324,24 +12485,24 @@ BEGIN ELSE INSERT INTO vncontrol.inter SET Id_Ticket = vTicket, - Id_Trabajador = SYSTEM_WORKER, + Id_Trabajador = vUserId, state_id = TICKET_FREE; END IF; - INSERT IGNORE INTO vn2008.order_Tickets - SET order_id = vOrder, - Id_Ticket = vTicket; + INSERT IGNORE INTO vn.orderTicket + SET orderFk = vOrder, + ticketFk = vTicket; -- Añade las notas IF vNotes IS NOT NULL AND vNotes != '' THEN - INSERT INTO vn2008.ticket_observation SET - Id_Ticket = vTicket, - observation_type_id = 4 /* salesperson */ , - `text` = vNotes + INSERT INTO vn.ticketObservation SET + ticketFk = vTicket, + observationTypeFk = 4 /* salesperson */ , + `description` = vNotes ON DUPLICATE KEY UPDATE - `text` = CONCAT(VALUES(`text`),'. ', `text`); + `description` = CONCAT(VALUES(`description`),'. ', `description`); END IF; -- Añade los movimientos y sus componentes @@ -12357,24 +12518,23 @@ BEGIN LEAVE lRows; END IF; - INSERT INTO vn2008.Movimientos + INSERT INTO vn.sale SET - Id_Article = vItem, - Id_Ticket = vTicket, - Concepte = vConcept, - Cantidad = vAmount, - Preu = vPrice, - CostFixat = 0, - PrecioFijado = TRUE; + itemFk = vItem, + ticketFk = vTicket, + concept = vConcept, + quantity = vAmount, + price = vPrice, + priceFixed = 0, + isPriceFixed = TRUE; SET vSale = LAST_INSERT_ID(); - INSERT INTO vn2008.Movimientos_componentes - (Id_Movimiento, Id_Componente, Valor) + INSERT INTO vn.saleComponent + (saleFk, componentFk, `value`) SELECT vSale, cm.component_id, cm.price FROM order_component cm - JOIN bi.tarifa_componentes tc - ON tc.Id_Componente = cm.component_id + JOIN vn.component c ON c.id = cm.component_id WHERE cm.order_row_id = vRowId GROUP BY vSale, cm.component_id; @@ -12391,20 +12551,17 @@ BEGIN CREATE TEMPORARY TABLE tComponents (INDEX (saleFk)) ENGINE = MEMORY - SELECT SUM(mc.Valor) valueSum, mc.Id_Movimiento saleFk - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc USING(Id_Componente) - JOIN bi.tarifa_componentes_series tcs - ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id - AND tcs.base - JOIN vn2008.Movimientos m - ON m.Id_Movimiento = mc.Id_Movimiento - WHERE m.Id_Ticket = vTicket - GROUP BY mc.Id_Movimiento; + SELECT SUM(sc.`value`) valueSum, sc.saleFk + FROM vn.saleComponent sc + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk AND ct.isBase + JOIN vn.sale s ON s.id = sc.saleFk + WHERE s.ticketFk = vTicket + GROUP BY sc.saleFk; - UPDATE vn2008.Movimientos m - JOIN tComponents mc ON mc.saleFk = m.Id_Movimiento - SET m.CostFixat = valueSum; + UPDATE vn.sale s + JOIN tComponents mc ON mc.saleFk = s.id + SET s.priceFixed = valueSum; DROP TEMPORARY TABLE tComponents; END LOOP; @@ -14871,6 +15028,21 @@ CREATE TABLE `currency` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `erte_COVID19` +-- + +DROP TABLE IF EXISTS `erte_COVID19`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `erte_COVID19` ( + `personFk` int(11) NOT NULL, + `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`personFk`), + CONSTRAINT `erte_COVID19_fk1` FOREIGN KEY (`personFk`) REFERENCES `person` (`person_id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `income_employee` -- @@ -14924,7 +15096,7 @@ CREATE TABLE `journey` ( `business_id` int(11) NOT NULL, PRIMARY KEY (`journey_id`), KEY `fki_business_journey` (`business_id`), - CONSTRAINT `business_journey` FOREIGN KEY (`business_id`) REFERENCES `business_labour` (`business_id`) ON DELETE CASCADE ON UPDATE CASCADE + CONSTRAINT `business_journey` FOREIGN KEY (`business_id`) REFERENCES `business` (`business_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; @@ -17899,6 +18071,8 @@ CREATE TABLE `XDiario` ( `FECREGCON` date DEFAULT NULL, PRIMARY KEY (`id`), KEY `empresa_id` (`empresa_id`), + KEY `ASIENidx` (`id`,`ASIEN`), + KEY `SERIEidx` (`ASIEN`,`SERIE`), CONSTRAINT `XDiario_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -18390,7 +18564,6 @@ CREATE TABLE `bank` ( `bank` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, `account` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, `cash` smallint(6) NOT NULL DEFAULT '0', - `warehouseFk__` smallint(5) unsigned NOT NULL DEFAULT '1', `entityFk` int(10) unsigned NOT NULL, `isActive` tinyint(4) NOT NULL DEFAULT '1', `currencyFk` tinyint(3) unsigned DEFAULT '1', @@ -18685,10 +18858,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_afterUpdate` - AFTER UPDATE ON `buy` - FOR EACH ROW -trig: BEGIN +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_afterUpdate` AFTER UPDATE ON `buy` FOR EACH ROW trig: BEGIN IF !(NEW.id <=> OLD.id) OR !(NEW.entryFk <=> OLD.entryFk) OR !(NEW.itemFk <=> OLD.itemFk) @@ -18703,7 +18873,7 @@ trig: BEGIN CALL buy_afterUpsert(NEW.id); - IF (!(NEW.weight <=> OLD.weight) OR !(NEW.packing <=> OLD.packing) OR !(NEW.packageFk <=> OLD.packageFk)) AND NEW.weight THEN + IF !(NEW.weight <=> OLD.weight) AND NEW.weight THEN UPDATE item SET density = NEW.weight / (item_getVolume(NEW.itemFk, NEW.packageFk) / 1000000) WHERE id = NEW.itemFk; @@ -19309,9 +19479,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -19361,6 +19531,18 @@ BEGIN LEFT JOIN account.account ac ON ac.id = u.id WHERE w.id = NEW.salesPersonFk; END IF; + + IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN + IF (SELECT COUNT(clientFk) + FROM clientProtected + WHERE clientFk = NEW.id + ) > 0 THEN + CALL util.throw("HAS_CLIENT_PROTECTED"); + END IF; + UPDATE vn2008.Clientes_cedidos + SET datEND = CURDATE() + WHERE Id_Cliente = NEW.id; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19526,48 +19708,6 @@ CREATE TABLE `clientManaCache` ( CONSTRAINT `cliente_fk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`clientManaCache_AFTER_INSERT` AFTER INSERT ON `clientManaCache` FOR EACH ROW -BEGIN - IF NEW.clientFk = 7157 THEN - INSERT INTO mail(sender, replyTo, `subject`, body) - SELECT 'carlosap@verdnatura.es','carlosap@verdnatura.es','Mana cliente 7157 ', CONCAT(current_user(), USER()); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`clientManaCache_AFTER_UPDATE` AFTER UPDATE ON `clientManaCache` FOR EACH ROW -BEGIN - IF NEW.clientFk = 7157 THEN - INSERT INTO mail(sender, replyTo, `subject`, body) - SELECT 'carlosap@verdnatura.es','carlosap@verdnatura.es','Mana cliente 7157 ', CONCAT(current_user(), USER()); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Temporary table structure for view `clientManaCache__` @@ -20170,6 +20310,7 @@ CREATE TABLE `conveyor` ( `height` int(11) DEFAULT NULL, `x` int(11) DEFAULT NULL, `y` int(11) DEFAULT NULL, + `color` int(11) DEFAULT '14548991', PRIMARY KEY (`id`), KEY `conveyor_fk1_idx` (`typeFk`), CONSTRAINT `conveyor_fk1` FOREIGN KEY (`typeFk`) REFERENCES `conveyorType` (`id`) ON UPDATE CASCADE @@ -20247,10 +20388,27 @@ CREATE TABLE `conveyorMode` ( `code` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `saturacion` int(11) NOT NULL, `gap` int(11) NOT NULL, + `isActive` tinyint(4) NOT NULL DEFAULT '0', PRIMARY KEY (`code`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `conveyorMove` +-- + +DROP TABLE IF EXISTS `conveyorMove`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `conveyorMove` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `fromConveyorFk` int(11) NOT NULL, + `toConveyorFk` int(11) NOT NULL, + `created` datetime NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `conveyorType` -- @@ -20611,7 +20769,7 @@ CREATE TABLE `customsAgent` ( `email` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `nif_UNIQUE` (`nif`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -20720,9 +20878,9 @@ CREATE TABLE `department` ( `rgt` int(11) DEFAULT NULL, `workerFk` int(11) DEFAULT NULL COMMENT 'Id_Trabajador es el jefe del departamento', `companyFk` int(11) NOT NULL, - `bossFk` int(11) DEFAULT NULL, - `x` int(11) DEFAULT NULL, - `y` int(11) DEFAULT NULL, + `bossFk__` int(11) DEFAULT NULL, + `x__` int(11) DEFAULT NULL, + `y__` int(11) DEFAULT NULL, `isProduction` tinyint(4) NOT NULL DEFAULT '0', `isSelected` tinyint(1) NOT NULL DEFAULT '0', `depth` int(11) NOT NULL DEFAULT '0', @@ -21809,6 +21967,23 @@ CREATE TABLE `expeditionBoxVol` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Establece el volumen de cada servicio para poder comparar el teorico y el real en el control de portes'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Temporary table structure for view `expeditionTimeExpended` +-- + +DROP TABLE IF EXISTS `expeditionTimeExpended`; +/*!50001 DROP VIEW IF EXISTS `expeditionTimeExpended`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `expeditionTimeExpended` AS SELECT + 1 AS `ticketFk`, + 1 AS `started`, + 1 AS `finished`, + 1 AS `cajas`, + 1 AS `code`, + 1 AS `warehouseFk`*/; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `expence` -- @@ -22090,7 +22265,7 @@ DROP TABLE IF EXISTS `intrastat`; CREATE TABLE `intrastat` ( `id` int(8) unsigned zerofill NOT NULL, `description` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `import` tinyint(4) NOT NULL DEFAULT '0', + `import__` tinyint(4) NOT NULL DEFAULT '0', `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '2', `taxCodeFk` tinyint(2) unsigned NOT NULL DEFAULT '64', PRIMARY KEY (`id`), @@ -22442,6 +22617,7 @@ CREATE TABLE `invoiceOutSerial` ( `taxAreaFk` varchar(15) CHARACTER SET utf8 NOT NULL DEFAULT 'NATIONAL', `isCEE` tinyint(1) NOT NULL DEFAULT '0', `cplusInvoiceType477Fk` int(10) unsigned DEFAULT '1', + `footNotes` longtext COLLATE utf8_unicode_ci, PRIMARY KEY (`code`), KEY `taxAreaFk_idx` (`taxAreaFk`), CONSTRAINT `invoiceOutSeriaTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE @@ -24067,6 +24243,23 @@ CREATE TABLE `mobileAppVersionControl` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla para llevar el control de las Versions de las aplicaciones móvil '; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `mrw` +-- + +DROP TABLE IF EXISTS `mrw`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `mrw` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `ticketFk` int(11) NOT NULL, + `counter` smallint(5) unsigned DEFAULT NULL, + `shipped` date DEFAULT NULL, + `price` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `noticeCategory` -- @@ -25033,7 +25226,8 @@ DROP TABLE IF EXISTS `punchState`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `punchState` ( `workerFk` int(11) NOT NULL, - `state` tinyint(4) DEFAULT '0', + `state` tinyint(4) DEFAULT '1', + `created` datetime DEFAULT NULL, PRIMARY KEY (`workerFk`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Table for storing punches that have cars with errors'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -25495,18 +25689,19 @@ DROP TABLE IF EXISTS `routeParams`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `routeParams` ( - `ID` int(10) unsigned NOT NULL AUTO_INCREMENT, + `id` int(10) unsigned NOT NULL, `kmRate` decimal(10,4) DEFAULT NULL, - `m3Distributed` decimal(10,4) DEFAULT NULL, + `m3Distribution` decimal(10,4) DEFAULT NULL, `m3Management` decimal(10,2) DEFAULT NULL, + `m3Palletization` decimal(10,2) DEFAULT NULL, `load1m3` decimal(10,4) DEFAULT NULL, `load2m3` decimal(10,4) DEFAULT NULL, `load3m3` decimal(10,4) DEFAULT NULL, `load4m3` decimal(10,4) DEFAULT NULL, `load5m3` decimal(10,4) DEFAULT NULL, `load6m3` decimal(10,4) DEFAULT NULL, - PRIMARY KEY (`ID`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -25845,27 +26040,6 @@ SET character_set_client = utf8; 1 AS `clientFk`*/; SET character_set_client = @saved_cs_client; --- --- Temporary table structure for view `saleVolume__` --- - -DROP TABLE IF EXISTS `saleVolume__`; -/*!50001 DROP VIEW IF EXISTS `saleVolume__`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `saleVolume__` AS SELECT - 1 AS `ticketFk`, - 1 AS `saleFk`, - 1 AS `litros`, - 1 AS `routeFk`, - 1 AS `shipped`, - 1 AS `volume`, - 1 AS `physicalWeight`, - 1 AS `weight`, - 1 AS `physicalVolume`, - 1 AS `freight`*/; -SET character_set_client = @saved_cs_client; - -- -- Temporary table structure for view `sale_freightComponent` -- @@ -25880,6 +26054,42 @@ SET character_set_client = utf8; 1 AS `shipped`*/; SET character_set_client = @saved_cs_client; +-- +-- Temporary table structure for view `salesPreparedLastHour` +-- + +DROP TABLE IF EXISTS `salesPreparedLastHour`; +/*!50001 DROP VIEW IF EXISTS `salesPreparedLastHour`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `salesPreparedLastHour` AS SELECT + 1 AS `warehouseFk`, + 1 AS `saleFk`, + 1 AS `isChecked`, + 1 AS `originalQuantity`, + 1 AS `accion`, + 1 AS `created`, + 1 AS `code`, + 1 AS `firstname`, + 1 AS `lastName`, + 1 AS `workerCode`, + 1 AS `litros`, + 1 AS `concept`, + 1 AS `departmentName`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary table structure for view `salesPreviousPreparated` +-- + +DROP TABLE IF EXISTS `salesPreviousPreparated`; +/*!50001 DROP VIEW IF EXISTS `salesPreviousPreparated`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `salesPreviousPreparated` AS SELECT + 1 AS `saleFk`*/; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `sample` -- @@ -26292,6 +26502,7 @@ CREATE TABLE `state` ( `isPreparable` tinyint(1) NOT NULL DEFAULT '0', `semaphore` int(11) NOT NULL DEFAULT '0', `isPrintable` tinyint(4) NOT NULL DEFAULT '0', + `isOK` tinyint(4) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `code_UNIQUE` (`code`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -26343,29 +26554,29 @@ DROP TABLE IF EXISTS `supplier`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `supplier` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `account` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `street` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `postCode__` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'deprecada', - `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, + `account` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, + `street` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, + `postCode__` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'deprecada', + `city` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `provinceFk` smallint(5) unsigned DEFAULT NULL, `countryFk` mediumint(8) unsigned DEFAULT NULL, - `nif` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `nif` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `isOfficial` tinyint(1) NOT NULL DEFAULT '1', `isFarmer` tinyint(1) NOT NULL DEFAULT '0', - `retAccount` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `phone` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL, - `Fax` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL, + `retAccount` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, + `phone` varchar(16) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, + `Fax` varchar(16) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `commission` float NOT NULL DEFAULT '0', - `nickname` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `nickname` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `payMethodFk` tinyint(3) unsigned NOT NULL, `payDay` tinyint(4) unsigned DEFAULT NULL, `payDemFk` tinyint(3) unsigned NOT NULL DEFAULT '7', `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `isSerious` tinyint(1) unsigned zerofill DEFAULT '1', - `note` text COLLATE utf8_unicode_ci, + `note` text CHARACTER SET utf8 COLLATE utf8_unicode_ci, `postcodeFk` int(11) unsigned DEFAULT NULL, - `postCode` char(5) COLLATE utf8_unicode_ci DEFAULT NULL, + `postCode` char(5) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `isActive` tinyint(4) DEFAULT '1', PRIMARY KEY (`id`), UNIQUE KEY `cuenta` (`account`), @@ -26379,7 +26590,7 @@ CREATE TABLE `supplier` ( CONSTRAINT `pay_dem_id` FOREIGN KEY (`payDemFk`) REFERENCES `payDem` (`id`) ON UPDATE CASCADE, CONSTRAINT `pay_met_id` FOREIGN KEY (`payMethodFk`) REFERENCES `payMethod` (`id`) ON UPDATE CASCADE, CONSTRAINT `province_id` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -26807,7 +27018,7 @@ BEGIN SET NEW.landed = DATE_FORMAT(NEW.landed, '2000-%m-%d %T'); SET NEW.routeFk = NULL; END IF; - + IF NEW.routeFk AND NEW.isDeleted THEN CALL util.throw ('This ticket is deleted'); END IF; @@ -27129,16 +27340,16 @@ CREATE TABLE `ticketPackaging` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketPackaging_BEFORE_INSERT` BEFORE INSERT ON `ticketPackaging` FOR EACH ROW BEGIN - SET NEW.workerFk = vn.getWorker(); + SET NEW.workerFk = vn.myWorker_getId(); END */;; DELIMITER ; @@ -28325,6 +28536,21 @@ SET character_set_client = utf8; 1 AS `departmentFk`*/; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `workerDisableExcluded` +-- + +DROP TABLE IF EXISTS `workerDisableExcluded`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `workerDisableExcluded` ( + `workerFk` int(11) NOT NULL, + `dated` date DEFAULT NULL, + PRIMARY KEY (`workerFk`), + CONSTRAINT `workerDisableExcludedFk1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='No se deshabilitan hasta la fecha especificada'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `workerDocument` -- @@ -28515,6 +28741,44 @@ SET character_set_client = utf8; 1 AS `mediaValue`*/; SET character_set_client = @saved_cs_client; +-- +-- Temporary table structure for view `workerSpeedExpedition` +-- + +DROP TABLE IF EXISTS `workerSpeedExpedition`; +/*!50001 DROP VIEW IF EXISTS `workerSpeedExpedition`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `workerSpeedExpedition` AS SELECT + 1 AS `ticketFk`, + 1 AS `litros`, + 1 AS `literLastHour`, + 1 AS `litersByMinute`, + 1 AS `workerCode`, + 1 AS `cajas`, + 1 AS `warehouseFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary table structure for view `workerSpeedSaleTracking` +-- + +DROP TABLE IF EXISTS `workerSpeedSaleTracking`; +/*!50001 DROP VIEW IF EXISTS `workerSpeedSaleTracking`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `workerSpeedSaleTracking` AS SELECT + 1 AS `warehouseFk`, + 1 AS `accion`, + 1 AS `workerCode`, + 1 AS `sumaLitros`, + 1 AS `started`, + 1 AS `finished`, + 1 AS `sumaLitrosLastHour`, + 1 AS `litersByMinute`, + 1 AS `departmentName`*/; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `workerTeam` -- @@ -28930,13 +29194,13 @@ CREATE TABLE `zone` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `zoneCalendar` +-- Table structure for table `zoneCalendar__` -- -DROP TABLE IF EXISTS `zoneCalendar`; +DROP TABLE IF EXISTS `zoneCalendar__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `zoneCalendar` ( +CREATE TABLE `zoneCalendar__` ( `zoneFk` int(11) NOT NULL, `delivered` date NOT NULL, `price` double NOT NULL, @@ -31952,10 +32216,10 @@ BEGIN */ DECLARE vWorker INT; - SELECT IFNULL(w.id, c.defaultWorkerFk) INTO vWorker + SELECT w.id INTO vWorker FROM worker w, workerConfig c WHERE w.userFk = account.userGetId(); - + RETURN vWorker; END ;; DELIMITER ; @@ -32574,13 +32838,14 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` FUNCTION `workerIsBoss`(vUserId INT) RETURNS int(11) + DETERMINISTIC BEGIN /** * Comprueba por jerarquía si el trabajador actual es jefe @@ -32613,7 +32878,7 @@ BEGIN END IF; IF vBossId = vWorkerId THEN RETURN FALSE; - ELSEIF vBossId = vn.getWorker() THEN + ELSEIF vBossId = vn.myWorker_getId() THEN RETURN TRUE; ELSE INSERT INTO tCheckedWorker VALUES (vWorkerId); @@ -33227,6 +33492,76 @@ BEGIN -- Establecemos los almacenes y las fechas que van a entrar al disponible + CALL vn.zone_getShipped (vDate, vAddress, vAgencyMode, FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; + CREATE TEMPORARY TABLE tmp.availableCalc( + calcFk INT UNSIGNED, + PRIMARY KEY (calcFk) + ) + ENGINE = MEMORY; + + OPEN cWarehouses; + + l: LOOP + SET vDone = FALSE; + FETCH cWarehouses INTO vWarehouse, vShipment; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh(vCalcFk, FALSE, vWarehouse, vShipment); + + INSERT IGNORE INTO tmp.availableCalc + SET calcFk = vCalcFk; + END LOOP; + + CLOSE cWarehouses; + DROP TEMPORARY TABLE tmp.zoneGetShipped; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `available_calc__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `available_calc__`( + vDate DATE, + vAddress INT, + vAgencyMode INT) +BEGIN +/** + * Calculates the available for all available stores + * according to the given parameters. + * + * @param vDate The delivery date + * @param vAddress The delivery address id + * @param vAgencyMode The shipping agency + * @return tmp.availableCalc(calcFk) The available cache ids + */ + DECLARE vCalcFk INT; + DECLARE vShipment DATE; + DECLARE vWarehouse INT; + DECLARE vDone BOOL; + + DECLARE cWarehouses CURSOR FOR + SELECT warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + -- Establecemos los almacenes y las fechas que van a entrar al disponible + CALL vn.zone_getShippedWarehouse(vDate, vAddress, vAgencyMode); DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; @@ -33925,6 +34260,132 @@ proc: BEGIN * @return tmp.ticketComponentPrice * @return tmp.zoneGetShipped + **/ + + DECLARE vAvailableCalc INT; + DECLARE vShipped DATE; + DECLARE vClient INT; + DECLARE vWarehouseFk SMALLINT; + DECLARE vZoneFk INT; + DECLARE vDone BOOL; + DECLARE cTravelTree CURSOR FOR + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + -- Establece los almacenes y las fechas que van a entrar al disponible + + SELECT clientFk INTO vClient + FROM address WHERE id = vAddressFk; + + CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `available` double DEFAULT NULL, + `buyFk` int(11) DEFAULT NULL, + `fix` tinyint(3) unsigned DEFAULT '0', + KEY `itemFk` (`itemFk`), + KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH + ) ENGINE=MEMORY DEFAULT CHARSET=utf8; + + OPEN cTravelTree; + + l: LOOP + SET vDone = FALSE; + FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); + CALL buyUltimate (vWarehouseFk, vShipped); + + INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) + SELECT vWarehouseFk, + i.item_id, + IFNULL(i.available, 0), + bu.buyFk + FROM `cache`.available i + JOIN tmp.item br ON br.itemFk = i.item_id + LEFT JOIN item it ON it.id = i.item_id + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id + WHERE i.calc_id = vAvailableCalc + AND it.id != 100 + AND i.available > 0; + + DROP TEMPORARY TABLE tmp.buyUltimate; + END LOOP; + + CLOSE cTravelTree; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; + CREATE TEMPORARY TABLE tmp.ticketCalculateItem + ENGINE = MEMORY + SELECT + b.itemFk, + SUM(b.available) available, + p.name producer, + i.name item, + i.size size, + i.stems, + i.category, + i.inkFk, + i.image, + o.code origin, + bl.price, + bl.priceKg + FROM tmp.ticketLot b + JOIN item i ON b.itemFk = i.id + LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible + JOIN origin o ON o.id = i.originFk + JOIN ( + SELECT MIN(price) price, itemFk, priceKg + FROM tmp.ticketComponentPrice + GROUP BY itemFk + ) bl ON bl.itemFk = b.itemFk + GROUP BY b.itemFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_calculate__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate__`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +/** + * Calcula los articulos disponibles y sus precios + * + * @table tmp.item(itemFk) Listado de artículos a calcular + * @param vLanded Fecha de recepcion de mercancia + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.ticketCalculateItem(itemFk, available, producer, + * item, size, stems, category, inkFk, image, origin, price) + * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) + * @return tmp.ticketComponent + * @return tmp.ticketComponentPrice + * @return tmp.zoneGetShipped + **/ DECLARE vAvailableCalc INT; @@ -34026,13 +34487,289 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`( + vZoneFk INT, + vAddressFk INT, + vShipped DATE) +proc: BEGIN +/** + * Calcula los componentes de los articulos de tmp.ticketLot + * + * @param vZoneFk para calcular el transporte + * @param vAddressFk Consignatario + * @param vShipped dia de salida del pedido + * @param tmp.ticketLot (warehouseFk,available,itemFk,buyFk) + * + * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, + * packing, grouping, groupingMode, buyFk, typeFk) + * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) + */ + DECLARE vClientFk INT; + DECLARE vGeneralInflationCoefficient INT DEFAULT 1; + DECLARE vMinimumDensityWeight INT DEFAULT 167; + DECLARE vBoxFreightItem INT DEFAULT 71; + DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; + DECLARE vSpecialPriceComponent INT DEFAULT 10; + DECLARE vDeliveryComponent INT DEFAULT 15; + DECLARE vRecoveryComponent INT DEFAULT 17; + DECLARE vSellByPacketComponent INT DEFAULT 22; + DECLARE vBuyValueComponent INT DEFAULT 28; + DECLARE vMarginComponent INT DEFAULT 29; + DECLARE vDiscountLastItemComponent INT DEFAULT 32; + DECLARE vExtraBaggedComponent INT DEFAULT 38; + DECLARE vManaAutoComponent INT DEFAULT 39; + + SELECT volume INTO vBoxVolume + FROM vn.packaging + WHERE id = '94'; + + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; + + SET @rate2 := 0; + SET @rate3 := 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT + tl.itemFk, tl.warehouseFk, tl.available, + IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, + IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, + IFNULL(pf.rate3, 0) AS minPrice, + IFNULL(pf.packing, b.packing) packing, + IFNULL(pf.`grouping`, b.`grouping`) `grouping`, + ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, + tl.buyFk, + i.typeFk, + IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping + FROM tmp.ticketLot tl + JOIN buy b ON b.id = tl.buyFk + JOIN item i ON i.id = tl.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk + LEFT JOIN ( + SELECT * FROM ( + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk + FROM priceFixed pf + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) + WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC + ) tpf + GROUP BY tpf.itemFk, tpf.warehouseFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + CREATE TEMPORARY TABLE tmp.ticketComponent ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `componentFk` INT UNSIGNED NOT NULL, + `cost` DECIMAL(10,4) NOT NULL, + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vBuyValueComponent, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vMarginComponent, + tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; + CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY + SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk + FROM tmp.ticketComponent tc + GROUP BY tc.itemFk, warehouseFk; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.priceIncreasing, 0.25), 3) + FROM tmp.ticketComponentBase tcb + JOIN claimRatio cr ON cr.clientFk = vClientFk + WHERE cr.priceIncreasing > 0.009; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto + FROM tmp.ticketComponentBase tcb + JOIN `client` c on c.id = vClientFk + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + WHERE wm.isPricesModifierActivated + HAVING manaAuto <> 0; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, + tcb.itemFk, + c.id, + GREATEST(IFNULL(ROUND(tcb.base * c.tax, 4), 0), tcc.minPrice - tcc.rate3) + FROM tmp.ticketComponentBase tcb + JOIN component c + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE c.id = vDiscountLastItemComponent AND c.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE sp.value IS NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.zone; + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.zone (INDEX (id)) + ENGINE = MEMORY + SELECT vZoneFk id; + + CALL zone_getOptionsForShipment(vShipped, TRUE); + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + vDeliveryComponent, + vGeneralInflationCoefficient + * ROUND(( + i.compression + * ic.cm3 + * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) + * IFNULL((zo.price - zo.bonus) + * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 + ) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN tmp.zoneOption zo ON zo.zoneFk = vZoneFk + JOIN zone z ON z.id = vZoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk + AND ic.itemFk = tcc.itemFk + HAVING cost <> 0; + + DROP TEMPORARY TABLE tmp.zoneOption; + + IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost + FROM tmp.ticketComponentCalculate tcc + JOIN vn.addressForPackaging ap + WHERE ap.addressFk = vAddressFk; + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; + CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY + SELECT * FROM tmp.ticketComponent; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + vSpecialPriceComponent, + sp.value - SUM(tcc.cost) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN component c ON c.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + WHERE c.classRate IS NULL + GROUP BY tcc.itemFk, tcc.warehouseFk + HAVING ABS(sumCost) > 0.001; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; + CREATE TEMPORARY TABLE tmp.ticketComponentSum + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, c.classRate + FROM tmp.ticketComponent tc + JOIN component c ON c.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, c.classRate; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; + CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY + SELECT tcc.warehouseFk, + tcc.itemFk, + 1 rate, + IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 1) = 1 + AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 2 rate, + tcc.packing `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 + AND tcc.packing > 0 AND tcc.available >= tcc.packing) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 3) = 3 + GROUP BY tcs.warehouseFk, tcs.itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY + SELECT * FROM ( + SELECT * FROM tmp.ticketComponentRate ORDER BY price + ) t + GROUP BY itemFk, warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketComponentCalculate, + tmp.ticketComponentSum, + tmp.ticketComponentBase, + tmp.ticketComponentRate, + tmp.ticketComponentCopy; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_componentCalculate__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8 */ ; /*!50003 SET character_set_results = utf8 */ ; /*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`( +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate__`( vZoneFk INT, vAddressFk INT, vShipped DATE) @@ -35177,13 +35914,72 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker`() +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vClientFk INT; + + DECLARE rs CURSOR FOR + SELECT c.clientFk + FROM tmp.clientGetDebt c + LEFT JOIN clientRisk r ON r.clientFk = c.clientFk + WHERE IFNULL(r.amount,0) = 0; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT cd.id as clientFk + FROM bs.clientDied cd + LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id + JOIN vn.client c ON c.id = cd.id + JOIN vn.province p ON p.id = c.provinceFk + JOIN vn.country co ON co.id = p.countryFk + WHERE cd.Aviso = 'TERCER AVISO' + AND cp.clientFk IS NULL + AND co.country NOT IN ('Portugal','Francia','España exento') + AND c.salesPersonFk IS NOT NULL; + + OPEN rs; + FETCH rs INTO vClientFk; + + WHILE NOT done DO + + CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); + UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; + + INSERT INTO vn.clientLog (originFk, userFk, `action`, description) + VALUES (vClientFk, account.userGetId(), 'update', CONCAT('Se ha desasignado el cliente por que no ha comprado en 3 meses')); + + REPLACE bs.clientNewBorn(clientFk, shipped) + VALUES(vClientFk, CURDATE()); + FETCH rs INTO vClientFk; + END WHILE; + + CLOSE rs; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientRemoveWorker__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker__`() BEGIN DECLARE done BOOL DEFAULT FALSE; DECLARE vClientFk INT; @@ -35696,6 +36492,30 @@ BEGIN LEFT JOIN vn.worker w ON w.id = c.salesPersonFk WHERE tc.collectionFk = vCollectionFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_get` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_get`(vWorkerFk INT) +BEGIN + + SELECT c.id AS collectionFk, date(c.created) AS created + FROM vn.collection c + JOIN vn.state s ON c.stateFk = s.id + WHERE c.workerFk = vWorkerFk AND s.code = 'ON_PREPARATION'; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35792,7 +36612,7 @@ proc:BEGIN AND a.name != 'REC_SILLA' AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE) AND s.isPrintable - AND (pb.m3 > 0.05 OR s.code = 'OK') + AND (pb.m3 > 0.05 OR s.isOK) ORDER BY (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , s.order DESC, Hora, @@ -35880,7 +36700,7 @@ proc:BEGIN -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; CREATE TEMPORARY TABLE tmp.ticketShelve - SELECT ticketFk, shelve + SELECT ticketFk, shelve, linesDif, LitersDif, heightDif FROM ( SELECT t.ticketFk, cv.`level` shelve, @@ -35900,6 +36720,7 @@ proc:BEGIN SELECT IFNULL(shelve,0) INTO vShelve FROM tmp.ticketShelve WHERE ticketFk = vFirstTicketFk + ORDER BY heightDif, litersDif, linesDif LIMIT 1; IF vShelve THEN @@ -35980,6 +36801,693 @@ proc:BEGIN SELECT vCollectionFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_newBeta` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_newBeta`(vSectorFk INT,vWorkerFk INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vMaxTickets INT DEFAULT 4; + DECLARE vStateFk INT; + DECLARE vFirstTicketFk INT; + DECLARE vWorkerCode VARCHAR(3); + DECLARE vShelve INT; + DECLARE vTicket INT; + DECLARE myUserIsSalesPersonRole BOOLEAN; + DECLARE vPrintedTickets INT; + DECLARE vMaxTicketPrinted INT DEFAULT 10; + + -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando + SELECT isPreviousPrepared, warehouseFk + INTO vIsPreviousPrepared, vWarehouseFk + FROM vn.sector + WHERE id = vSectorFk; + + IF vIsPreviousPrepared THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + -- Averiguamos si es comercial el usuario + SELECT (r.name = 'salesPerson') + INTO myUserIsSalesPersonRole + FROM account.user u + JOIN account.role r ON r.id = u.role + WHERE u.id = vWorkerFk; + + -- Obtenemos el código del usuario + SELECT w.code + INTO vWorkerCode + FROM vn.worker w + WHERE w.id = vWorkerFk; + + -- Se obtiene nº de colección y el buffer con los pedidos preparables + INSERT INTO vn.collection + SET workerFk = vWorkerFk; + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + CALL vn2008.production_control_source(vWarehouseFk, 0); + + SELECT COUNT(*) INTO vPrintedTickets + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + WHERE pb.Fecha = CURDATE() + AND s.isPreparable; + + SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; + + -- AutoPRINT + + IF vMaxTicketPrinted > 0 THEN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT s2.id, pb.Id_Ticket, vWorkerFk + FROM tmp.production_buffer pb + JOIN vn.agency a ON a.id = pb.agency_id + JOIN vn.state s ON s.id = pb.state + JOIN vn.state s2 ON s2.code = 'PRINTED' + LEFT JOIN vn.route r ON r.id = pb.Id_Ruta + WHERE pb.Fecha = CURDATE() + AND NOT pb.problems + AND a.name != 'REC_SILLA' + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE) + AND s.isPrintable + AND (pb.m3 > 0.05 OR s.isOK) + ORDER BY (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , + s.order DESC, + Hora, + minuto, + IFNULL(r.priority,99999), + pb.m3 DESC + LIMIT vMaxTicketPrinted; + + END IF; + + -- SELECT vMaxTicketPrinted; + -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. + + INSERT IGNORE INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT pb.Id_Ticket, + vCollectionFk + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + WHERE pb.collectionFk IS NULL + AND ( + (s.isPreparable AND NOT myUserIsSalesPersonRole AND pb.Agencia != 'REC_SILLA') + OR + (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) + ) + ORDER BY (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) DESC, pb.Hora, pb.Minuto + LIMIT vMaxTickets; + + + -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT pb.Id_Ticket ticketFk, + pb.lines, + pb.m3 * 1000 liters, + 0 as height, + 0 as shelve + FROM tmp.production_buffer pb + JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket + WHERE tc.collectionFk = vCollectionFk; + + /* El criterio para formar la colección es el siguiente: + * + * 1º.- Los tickets asignados son prioritarios, y por ello ya vienen ordenados en las primeras posiciones. + * 2º.- Las recogidas en Silla tienen que ir en carros independientes. + * + * Por tanto, si el primer pedido es recogida, nos olvidamos del resto. + * Si el primer pedido no es recogida, eliminamos las recogidas posteriores. + */ + + SELECT ticketFk + INTO vFirstTicketFk + FROM tmp.ticket + LIMIT 1; + + IF (SELECT pb.Agencia FROM tmp.production_buffer pb WHERE Id_Ticket = vFirstTicketFk) = 'REC_SILLA' THEN + + DELETE FROM tmp.ticket WHERE ticketFk != vFirstTicketFk; + + UPDATE tmp.ticket SET shelve = 1; + -- Como sólo hay un ticket, se le asigna el nivel 1 y acabamos + + ELSE + + -- Eliminamos los de recogida, puesto que el primero sabemos que no es de rec_silla + DELETE t.* + FROM tmp.ticket t + JOIN tmp.production_buffer pb ON pb.Id_Ticket = t.ticketFk + WHERE pb.Agencia = 'REC_SILLA'; + + -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. + UPDATE tmp.ticket t + JOIN + ( SELECT MAX(i.size) maxHeigth, + tc.ticketFk + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.isReclining = FALSE + AND tc.collectionFk = vCollectionFk + GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk + SET t.height = sub.maxHeigth; + + -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido + DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; + CREATE TEMPORARY TABLE tmp.ticketShelve + SELECT ticketFk, shelve, linesDif, LitersDif, heightDif + FROM ( + SELECT t.ticketFk, + cv.`level` shelve, + CAST(cv.lines AS SIGNED) - t.lines as linesDif, + CAST(cv.liters AS SIGNED) - t.liters as litersDif, + CAST(cv.height AS SIGNED) - t.height as heightDif + FROM vn.collectionVolumetry cv + JOIN tmp.ticket t + ORDER BY (t.ticketFk = vFirstTicketFk) DESC, linesDif + ) sub + WHERE linesDif >= 0 + AND litersDif >= 0 + AND heightDif >= 0 + ORDER BY linesDif; + + -- Asignamos la primera balda util al primer pedido + SELECT IFNULL(shelve,0) INTO vShelve + FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + IF vShelve THEN + + UPDATE tmp.ticket + SET shelve = vShelve + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + OR shelve = vShelve; + + WHILE (SELECT COUNT(*) FROM tmp.ticketShelve) DO + + SELECT ticketFk, shelve + INTO vTicket, vShelve + FROM tmp.ticketShelve + LIMIT 1; + + UPDATE tmp.ticket + SET shelve = vShelve + WHERE ticketFk = vTicket; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vTicket + OR shelve = vShelve; + + END WHILE; + + ELSE + + UPDATE tmp.ticket + SET shelve = 1 + WHERE ticketFk = vFirstTicketFk; + + END IF; + + END IF; + + -- Eliminamos los que se han quedado sin balda + DELETE FROM tmp.ticket WHERE shelve = 0 ; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + -- Actualiza el estado de la colección + UPDATE vn.collection c + JOIN vn.state st ON st.code = 'ON_PREPARATION' + SET c.stateFk = st.id + WHERE c.id = vCollectionFk; + + -- Asigna las bandejas + UPDATE vn.ticketCollection tc + JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + SET tc.level = t.shelve; + + -- Actualiza el estado de los tickets + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT vStateFk, ticketFk, vWorkerFk + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + -- Avisa los preparados previos que hay que bajar del altillo imprimiendo etiqueta + INSERT IGNORE INTO vn.ticketDown(ticketFk) + SELECT DISTINCT tc.ticketFk + FROM vn.ticketCollection tc + JOIN vncontrol.inter vi ON vi.Id_Ticket = tc.ticketFk + JOIN vn.state st ON st.id = vi.state_id + JOIN vn.ticket t ON t.id = tc.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + WHERE tc.collectionFk = vCollectionFk + AND w.name = 'Silla FV' + AND st.code = 'PREVIOUS_PREPARATION'; + + SELECT vCollectionFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_new_test` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_new_test`(vSectorFk INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vMaxTickets INT DEFAULT 4; + DECLARE vStateFk INT; + DECLARE vFirstTicketFk INT; + DECLARE vWorkerCode VARCHAR(3); + DECLARE vShelve INT; + DECLARE vTicket INT; + DECLARE myUserIsSalesPersonRole BOOLEAN; + DECLARE vPrintedTickets INT; + DECLARE vMaxTicketPrinted INT DEFAULT 10; + + DROP TEMPORARY TABLE IF EXISTS tmp.log; + CREATE TEMPORARY TABLE tmp.log + SELECT CURTIME() as hora, + 'Comienza el proc ' as accion, + ' -- ' as valor; + + -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando + SELECT isPreviousPrepared, warehouseFk + INTO vIsPreviousPrepared, vWarehouseFk + FROM vn.sector + WHERE id = vSectorFk; + + IF vIsPreviousPrepared THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + -- Averiguamos si es comercial el usuario + SELECT (r.name = 'salesPerson') + INTO myUserIsSalesPersonRole + FROM account.user u + JOIN account.role r ON r.id = u.role + WHERE u.id = vn.getUser(); + + INSERT INTO tmp.log(hora, + accion, + valor) + VALUES( CURTIME(), + 'Determina si es comercial el usuario', + myUserIsSalesPersonRole); + + -- Obtenemos el código del usuario + SELECT w.code + INTO vWorkerCode + FROM vn.worker w + WHERE w.id = account.myUserGetId(); + + -- Se obtiene nº de colección y el buffer con los pedidos preparables + INSERT INTO vn.collection + SET workerFk = account.myUserGetId(); + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + INSERT INTO tmp.log(hora, + accion, + valor) + VALUES( CURTIME(), + 'Obtiene numero de coleccion', + vCollectionFk); + + + + CALL vn2008.production_control_source(vWarehouseFk, 0); + + SELECT COUNT(*) INTO vPrintedTickets + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + WHERE pb.Fecha = CURDATE() + AND s.isPreparable; + + + INSERT INTO tmp.log(hora, + accion, + valor) + VALUES( CURTIME(), + 'Calcula tickets impresos', + vPrintedTickets); + + + + SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; + + -- AutoPRINT + + IF vMaxTicketPrinted > 0 THEN + + + INSERT INTO tmp.log(hora, + accion, + valor) + SELECT CURTIME(), + CONCAT('T', pb.Id_Ticket), +'PRINTED' + FROM tmp.production_buffer pb + JOIN vn.agency a ON a.id = pb.agency_id + JOIN vn.state s ON s.id = pb.state + JOIN vn.state s2 ON s2.code = 'PRINTED' + LEFT JOIN vn.route r ON r.id = pb.Id_Ruta + WHERE pb.Fecha = CURDATE() + AND NOT pb.problems + AND a.name != 'REC_SILLA' + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE) + AND s.isPrintable + AND (pb.m3 > 0.05 OR s.isOK) + ORDER BY (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , + s.order DESC, + Hora, + minuto, + IFNULL(r.priority,99999), + pb.m3 DESC + LIMIT vMaxTicketPrinted; + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT s2.id, pb.Id_Ticket, vn.getUser() + FROM tmp.production_buffer pb + JOIN vn.agency a ON a.id = pb.agency_id + JOIN vn.state s ON s.id = pb.state + JOIN vn.state s2 ON s2.code = 'PRINTED' + LEFT JOIN vn.route r ON r.id = pb.Id_Ruta + WHERE pb.Fecha = CURDATE() + AND NOT pb.problems + AND a.name != 'REC_SILLA' + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE) + AND s.isPrintable + AND (pb.m3 > 0.05 OR s.isOK) + ORDER BY (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , + s.order DESC, + Hora, + minuto, + IFNULL(r.priority,99999), + pb.m3 DESC + LIMIT vMaxTicketPrinted; + + END IF; + + -- SELECT vMaxTicketPrinted; + -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. + + INSERT IGNORE INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT pb.Id_Ticket, + vCollectionFk + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + WHERE pb.collectionFk IS NULL + AND ( + (s.isPreparable AND NOT myUserIsSalesPersonRole AND pb.Agencia != 'REC_SILLA') + OR + (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) + ) + ORDER BY (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) DESC, pb.Hora, pb.Minuto + LIMIT vMaxTickets; + + + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),ticketFk,vCollectionFk + FROM vn.ticketCollection + WHERE collectionFk = vCollectionFk; + + + -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT pb.Id_Ticket ticketFk, + pb.lines, + pb.m3 * 1000 liters, + 0 as height, + 0 as shelve + FROM tmp.production_buffer pb + JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket + WHERE tc.collectionFk = vCollectionFk; + + + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),ticketFk,CONCAT('Ln:',`lines`,' Lt:',liters,' h:',height,' sh:',shelve) + FROM tmp.ticket; + + /* El criterio para formar la colección es el siguiente: + * + * 1º.- Los tickets asignados son prioritarios, y por ello ya vienen ordenados en las primeras posiciones. + * 2º.- Las recogidas en Silla tienen que ir en carros independientes. + * + * Por tanto, si el primer pedido es recogida, nos olvidamos del resto. + * Si el primer pedido no es recogida, eliminamos las recogidas posteriores. + */ + + SELECT ticketFk + INTO vFirstTicketFk + FROM tmp.ticket + LIMIT 1; + + + INSERT INTO tmp.log(hora, accion, valor) + VALUES( CURTIME(),'Primer ticket',vFirstTicketFk) + ; + + IF (SELECT pb.Agencia FROM tmp.production_buffer pb WHERE Id_Ticket = vFirstTicketFk) = 'REC_SILLA' THEN + + DELETE FROM tmp.ticket WHERE ticketFk != vFirstTicketFk; + + UPDATE tmp.ticket SET shelve = 1; + -- Como sólo hay un ticket, se le asigna el nivel 1 y acabamos + + ELSE + + -- Eliminamos los de recogida, puesto que el primero sabemos que no es de rec_silla + DELETE t.* + FROM tmp.ticket t + JOIN tmp.production_buffer pb ON pb.Id_Ticket = t.ticketFk + WHERE pb.Agencia = 'REC_SILLA'; + + -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. + UPDATE tmp.ticket t + JOIN + ( SELECT MAX(i.size) maxHeigth, + tc.ticketFk + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.isReclining = FALSE + AND tc.collectionFk = vCollectionFk + GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk + SET t.height = sub.maxHeigth; + + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),ticketFk,CONCAT('Ln:',`lines`,' Lt:',liters,' h:',height,' sh:',shelve) + FROM tmp.ticket; + + + -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido + DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; + CREATE TEMPORARY TABLE tmp.ticketShelve + SELECT ticketFk, shelve, linesDif, litersDif, heightDif + FROM ( + SELECT t.ticketFk, + cv.`level` shelve, + CAST(cv.lines AS SIGNED) - t.lines as linesDif, + CAST(cv.liters AS SIGNED) - t.liters as litersDif, + CAST(cv.height AS SIGNED) - t.height as heightDif + FROM vn.collectionVolumetry cv + JOIN tmp.ticket t + ORDER BY (t.ticketFk = vFirstTicketFk) DESC, linesDif + ) sub + WHERE linesDif >= 0 + AND litersDif >= 0 + AND heightDif >= 0 + ORDER BY linesDif; + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),'Todas las posibilidades',COUNT(*) + FROM tmp.ticketShelve; + + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),ticketFk,CONCAT('Lnd:',`linesDif`,' Ltd',litersDif,' hd:',heightDif,' sh:',shelve) + FROM tmp.ticketShelve; + + -- Asignamos la primera balda util al primer pedido + SELECT IFNULL(shelve,0) INTO vShelve + FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),'vShelve',vShelve; + IF vShelve THEN + + UPDATE tmp.ticket + SET shelve = vShelve + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + OR shelve = vShelve; + + WHILE (SELECT COUNT(*) FROM tmp.ticketShelve) DO + + SELECT ticketFk, shelve + INTO vTicket, vShelve + FROM tmp.ticketShelve + LIMIT 1; + + UPDATE tmp.ticket + SET shelve = vShelve + WHERE ticketFk = vTicket; + + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),'Quedan', COUNT(*) + FROM tmp.ticketShelve; + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),ticketFk,CONCAT(' sh:',shelve) + FROM tmp.ticket; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vTicket + OR shelve = vShelve; + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),'Borrar los asignados', COUNT(*) + FROM tmp.ticketShelve + WHERE ticketFk = vTicket + OR shelve = vShelve; + + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),ticketFk,CONCAT(' sh:',shelve) + FROM tmp.ticket; + + END WHILE; + + + ELSE + + UPDATE tmp.ticket + SET shelve = 1 + WHERE ticketFk = vFirstTicketFk; + + END IF; + + END IF; + + -- Eliminamos los que se han quedado sin balda + DELETE FROM tmp.ticket WHERE shelve = 0 ; + + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),ticketFk,CONCAT('Borrar sh:',shelve) + FROM tmp.ticket + WHERE shelve = 0; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + INSERT INTO tmp.log(hora, accion, valor) + SELECT CURTIME(),'Elimina tickets bloqueados', tc.ticketFk + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + + -- Actualiza el estado de la colección + UPDATE vn.collection c + JOIN vn.state st ON st.code = 'ON_PREPARATION' + SET c.stateFk = st.id + WHERE c.id = vCollectionFk; + + -- Asigna las bandejas + UPDATE vn.ticketCollection tc + JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + SET tc.level = t.shelve; + + -- Actualiza el estado de los tickets + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT vStateFk, ticketFk, account.myUserGetId() + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + -- Avisa los preparados previos que hay que bajar del altillo imprimiendo etiqueta + INSERT IGNORE INTO vn.ticketDown(ticketFk) + SELECT DISTINCT tc.ticketFk + FROM vn.ticketCollection tc + JOIN vncontrol.inter vi ON vi.Id_Ticket = tc.ticketFk + JOIN vn.state st ON st.id = vi.state_id + JOIN vn.ticket t ON t.id = tc.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + WHERE tc.collectionFk = vCollectionFk + AND w.name = 'Silla FV' + AND st.code = 'PREVIOUS_PREPARATION'; + + SELECT * FROM tmp.log; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36038,8 +37546,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `conveyorExpedition_Add`(vDate DATE) BEGIN - DELETE FROM vn.conveyorExpedition - WHERE date(created) = vDate; + TRUNCATE vn.conveyorExpedition; INSERT INTO vn.conveyorExpedition( expeditionFk, created, @@ -36085,8 +37592,6 @@ BEGIN AND t.warehouseFk = 44 AND e.isBox = 71; - - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -37835,7 +39340,74 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `entryWithItem`(IN `vShipmentWarehouse` INT, IN `vLandingWarehouse` INT, IN `vSale` INT, IN `vVolume` INT, IN netCost DECIMAL(10,2), IN `vInOutDate` DATE) +CREATE DEFINER=`root`@`%` PROCEDURE `entryWithItem`(vShipmentWarehouse INT, vLandingWarehouse INT,vSale INT, vVolume INT, netCost DECIMAL(10,2), vInOutDate DATE) +BEGIN + + DECLARE vTravel INT; + DECLARE vEntry INT; + DECLARE vBucket VARCHAR(10); + DECLARE vSupplierFk INT; + + SET vSupplierFk = IF (vLandingWarehouse = 1, 850, 963); + -- seleccionamos travel + SELECT t.id, e.id INTO vTravel, vEntry + FROM travel t LEFT JOIN entry e ON t.id = e.travelFk + WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse + AND t.warehouseInFk = vLandingWarehouse AND t.agencyFk IS NULL AND e.supplierFk = vSupplierFk + LIMIT 1; + + -- creamos el travel si es necesario + IF IFNULL(vTravel, FALSE) = FALSE THEN + INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk) + VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse); + SELECT LAST_INSERT_ID() INTO vTravel; + END IF; + + -- creamos la Entrada si es necesario + IF IFNULL(vEntry, FALSE) = FALSE THEN + INSERT INTO entry (supplierFk, travelFk) + VALUES (vSupplierFk, vTravel); -- proveedor 'CONFECCION ARTIFICIAL' + SELECT LAST_INSERT_ID() INTO vEntry; + END IF; + + -- creamos el cubo si es necesario + SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; + IF vBucket IS NULL THEN + INSERT INTO packaging (id, volume) + VALUES (CONCAT('dm',vVolume/1000), vVolume); + -- SELECT LAST_INSERT_ID() INTO vBucket; + SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; + END IF; + + INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) + SELECT itemFk, + quantity, + vEntry, + vBucket, + 1 packing, + quantity, + netCost, + s.price, + s.price + FROM sale s + WHERE s.id = vSale; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `entryWithItem__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `entryWithItem__`(IN `vShipmentWarehouse` INT, IN `vLandingWarehouse` INT, IN `vSale` INT, IN `vVolume` INT, IN netCost DECIMAL(10,2), IN `vInOutDate` DATE) BEGIN DECLARE vTravel INT; @@ -37871,7 +39443,8 @@ BEGIN IF vBucket IS NULL THEN INSERT INTO packaging (id, volume) VALUES (CONCAT('dm',vVolume/1000), vVolume); - SELECT LAST_INSERT_ID() INTO vBucket; + -- SELECT LAST_INSERT_ID() INTO vBucket; + SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; END IF; INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, `grouping`, stickers, buyingValue, price2, price3) @@ -40640,9 +42213,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -40664,7 +42237,7 @@ BEGIN DECLARE vSpainCountryCode INT DEFAULT 1; DECLARE vIsAnySaleToInvoice BOOL; DECLARE vNewRef VARCHAR(255); - DECLARE vWorker INT DEFAULT vn.getWorker(); + DECLARE vWorker INT DEFAULT vn.myWorker_getId(); DECLARE vCompany INT; DECLARE vClient INT; DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1; @@ -40696,7 +42269,9 @@ BEGIN JOIN ticket t ON t.id = ti.id JOIN client c ON c.id = t.clientFk WHERE YEAR(t.shipped) < 2001 - OR c.isTaxDataChecked = FALSE; + OR c.isTaxDataChecked = FALSE + OR t.isDeleted + OR c.hasToInvoice = FALSE; SELECT SUM(quantity * price * (100 - discount)/100) INTO vIsAnySaleToInvoice @@ -41769,16 +43344,24 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementSupplyStockGetTargetList`(vItemFk INT,vSectorFk INT) BEGIN - SELECT shelving, parking, sum(stock) as stockTotal,created + DECLARE vWarehouseFk INT; + DECLARE vWarehouseAliasFk INT; + + SELECT s.warehouseFk , w.aliasFk INTO vWarehouseFk, vWarehouseAliasFk + FROM vn.sector s + JOIN vn.warehouse w ON w.id = s.warehouseFk + WHERE s.id = vSectorFk; + + SELECT shelving, parking, sum(stock) as stockTotal,created,`order` FROM ( SELECT `ispss`.`itemShelvingFk` AS `itemShelvingFk`, @@ -41794,12 +43377,20 @@ BEGIN `ispss`.`created` AS `created`, `ispss`.`priority` AS `priority`, `ispss`.`parkingFk` AS `parkingFk`, - `ispss`.`sectorFk` AS `sectorFk` + `ispss`.`sectorFk` AS `sectorFk`, + IFNULL(cpd.id,0) as `order` FROM vn.itemShelvingPlacementSupplyStock ispss - LEFT JOIN vn.parking p ON p.code = parking - WHERE itemFk = vItemFk - -- AND p.sectorFk = vSectorFk + JOIN vn.itemShelving ish ON ish.itemFk = vItemFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + LEFT JOIN vn.coolerPathDetail cpd ON CAST(cpd.hallway AS DECIMAL(3,0)) = p.column + JOIN vn.sector sc ON sc.id = p.sectorFk + JOIN vn.warehouse w ON w.id = sc.warehouseFk + WHERE ispss.itemFk = vItemFk + AND w.aliasFk = vWarehouseAliasFk + -- AND p.sectorFk = vSectorFk AND stock > 0 + AND ispss.sectorFk IN (SELECT id FROM vn.sector WHERE warehouseFk = vWarehouseFk) ORDER BY priority DESC ) sub GROUP BY shelving @@ -43353,7 +44944,7 @@ BEGIN CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/ , vWarehouse, vDate); CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); - SELECT visible INTO vVisibleAltillo + SELECT SUM(visible) INTO vVisibleAltillo FROM vn.itemShelvingStock WHERE itemFk = vItem AND warehouseFk = vWarehouse; @@ -44897,7 +46488,7 @@ BEGIN SET valueFk = (IFNULL(valueFk,0) + 1) MOD 3; REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk) - VALUES(saleFk,valueFk,getWorker(),encajando); + VALUES(saleFk,valueFk,myWorker_getId(),encajando); END ;; @@ -45039,9 +46630,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -45060,7 +46651,7 @@ BEGIN DECLARE vShipmentHour VARCHAR(10); SELECT getTicketTrolleyLabelCount(vTicket) INTO vLabelCount; - SELECT getWorker() INTO vWorker; + SELECT myWorker_getId() INTO vWorker; SELECT CONCAT(getShipmentHour(vTicket),':00') INTO vShipmentHour; INSERT INTO printingQueue(printer @@ -45728,9 +47319,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -45749,7 +47340,7 @@ BEGIN WHERE s.ticketFk = vTicketFk; REPLACE vn2008.Movimientos_mark(Id_Movimiento, Valor, original_quantity, Id_Trabajador, stateFk) - SELECT s.id, s.isPicked, s.quantity, getWorker(), vStateFk + SELECT s.id, s.isPicked, s.quantity, myWorker_getId(), vStateFk FROM sale s JOIN vn.saleItemShelving sis ON sis.saleFk = s.id WHERE s.ticketFk = vTicketFk; @@ -45852,9 +47443,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -45903,7 +47494,7 @@ BEGIN END IF; INSERT INTO ticketTracking(ticketFk, workerFk, stateFk) - SELECT vNewTicket, getWorker(), s.id + SELECT vNewTicket, myWorker_getId(), s.id FROM state s WHERE s.code = 'FIXING'; @@ -46367,6 +47958,28 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sector_get` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `sector_get`() +BEGIN + + SELECT s.id,s.description,s.warehouseFk + FROM vn.sector s; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `setPlacementReserve` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -47050,24 +48663,24 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stowawayBoarding` */; +/*!50003 DROP PROCEDURE IF EXISTS `stowawayBoarding__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stowawayBoarding`(IN vShipFk INT, IN vStowawayFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `stowawayBoarding__`(IN vShipFk INT, IN vStowawayFk INT) BEGIN REPLACE stowaway(shipFk, id) VALUES (vShipFk, vStowawayFk); INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vShipFk, getWorker() + SELECT id, vShipFk, myWorker_getId() FROM state WHERE code = 'BOARDING'; @@ -48096,18 +49709,18 @@ BEGIN CALL ticketClosure(); - INSERT INTO mail (sender, replyTo, subject, body) - SELECT 'jgallego@verdnatura.es', 'jgallego@verdnatura.es', 'Tickets enrutados y NO preparados', - GROUP_CONCAT(ticketFk) tickets - FROM ticket t + -- cau 15033 + UPDATE ticket t JOIN ticketState ts ON t.id = ts.ticketFk JOIN alertLevel al ON al.alertLevel = ts.alertLevel JOIN agencyMode am ON am.id = t.agencyModeFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + JOIN zone z ON z.id = t.zoneFk + SET t.routeFk = NULL WHERE shipped BETWEEN vDateTo AND vDateToEndDay AND al.code NOT IN('DELIVERED','PACKED') AND t.routeFk - HAVING tickets IS NOT NULL; + AND z.`name` LIKE '%MADRID%'; DROP TEMPORARY TABLE tmp.ticketClosure; END ;; @@ -48134,7 +49747,8 @@ BEGIN * * @param vDate Fecha del cierre */ - + DECLARE vDateToEndDay DATETIME DEFAULT util.dayEnd(vDateTo); + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY ( @@ -48160,7 +49774,7 @@ BEGIN JOIN alertLevel al ON al.alertLevel = ts.alertLevel JOIN agencyMode am ON am.id = t.agencyModeFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - WHERE shipped = TIMESTAMPADD(DAY, -1, CURDATE()) + WHERE shipped BETWEEN vDateTo AND vDateToEndDay AND al.code NOT IN('DELIVERED','PACKED') AND t.routeFk HAVING tickets IS NOT NULL; @@ -48598,13 +50212,110 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( + vClientId INT + ,vShipped DATE + ,vWarehouseFk INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyModeFk INT + ,vRouteFk INT + ,vlanded DATE + ,vUserId INT + ,OUT vNewTicket INT) +BEGIN + + DECLARE vZoneFk INT; + + IF vClientId IS NULL THEN + CALL util.throw ('CLIENT_NOT_ESPECIFIED'); + END IF; + + IF NOT vAddressFk OR vAddressFk IS NULL THEN + SELECT id INTO vAddressFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN + SELECT agencyModeFk INTO vAgencyModeFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); + + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + INSERT INTO vn2008.Tickets ( + Id_Cliente, + Fecha, + Id_Consigna, + Id_Agencia, + Alias, + warehouse_id, + Id_Ruta, + empresa_id, + landing, + zoneFk + ) + SELECT + vClientId, + vShipped, + a.id, + IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), + a.nickname, + vWarehouseFk, + IF(vRouteFk,vRouteFk,NULL), + vCompanyFk, + vlanded, + vZoneFk + FROM address a + JOIN agencyMode am ON am.id = a.agencyModeFk + WHERE a.id = vAddressFk; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN address a ON a.id = ao.addressFk + WHERE a.id = vAddressFk; + + -- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket)); + INSERT INTO vn.ticketLog + SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); + + IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vNewTicket, vUserId + FROM state + WHERE `code` = 'DELIVERED'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCreateWithoutZone__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8 */ ; /*!50003 SET character_set_results = utf8 */ ; /*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone__`( vClientId INT ,vShipped DATE ,vWarehouseFk INT @@ -48695,13 +50406,116 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( + vClientId INT + ,vShipped DATE + ,vWarehouseFk INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyModeFk INT + ,vRouteFk INT + ,vlanded DATE + ,vUserId INT + ,OUT vNewTicket INT) +BEGIN + + DECLARE vZoneFk INT; + DECLARE vPrice DECIMAL(10,2); + DECLARE vBonus DECIMAL(10,2); + + IF vClientId IS NULL THEN + CALL util.throw ('CLIENT_NOT_ESPECIFIED'); + END IF; + + IF NOT vAddressFk OR vAddressFk IS NULL THEN + SELECT id INTO vAddressFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + IF vAgencyModeFk IS NOT NULL THEN + + CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); + + SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus + FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + IF vZoneFk IS NULL OR vZoneFk = 0 THEN + CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); + END IF; + END IF; + INSERT INTO ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + routeFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus + ) + SELECT + vClientId, + vShipped, + a.id, + vAgencyModeFk, + a.nickname, + vWarehouseFk, + IF(vRouteFk,vRouteFk,NULL), + vCompanyFk, + vlanded, + vZoneFk, + vPrice, + vBonus + FROM address a + JOIN agencyMode am ON am.id = a.agencyModeFk + WHERE a.id = vAddressFk; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN address a ON a.id = ao.addressFk + WHERE a.id = vAddressFk; + + INSERT INTO vn.ticketLog + SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); + + IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vNewTicket, myWorker_getId() + FROM state + WHERE `code` = 'DELIVERED'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCreateWithUser__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8 */ ; /*!50003 SET character_set_results = utf8 */ ; /*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser__`( vClientId INT ,vShipped DATE ,vWarehouseFk INT @@ -49424,7 +51238,7 @@ BEGIN FROM vn.ticketParking WHERE ticketFk = vTicketFk; - SELECT tp.ticketFk, CONCAT(vCollectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp JOIN vn.parking p ON p.id = tp.parkingFk JOIN vn.sector sc ON sc.id = p.sectorFk @@ -49590,9 +51404,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -49629,7 +51443,7 @@ BEGIN WHERE inter_id = vControlFk; */ INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador, Id_Supervisor) - SELECT s.nextStateFk, i.Id_Ticket, vLastWorkerFk, vn.getWorker() + SELECT s.nextStateFk, i.Id_Ticket, vLastWorkerFk, vn.myWorker_getId() FROM vncontrol.inter i JOIN vn.state s ON i.state_id = s.id WHERE inter_id = vControlFk; @@ -49657,9 +51471,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -49667,7 +51481,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticketStateUpdate`(vTicketFk INT, vStateCod BEGIN INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vTicketFk, getWorker() + SELECT id, vTicketFk, myWorker_getId() FROM vn.state WHERE `code` = vStateCode collate utf8_unicode_ci; @@ -50470,7 +52284,8 @@ BEGIN OPEN vCursor; REPEAT FETCH vCursor INTO vFechedTicket, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk; - CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); + UPDATE vn.ticket t JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = vWarehouseFk SET t.zoneFk = zgs.zoneFk @@ -50585,7 +52400,7 @@ proc: BEGIN FROM ticket WHERE id = vTicketFk; - CALL zone_getShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); + CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra @@ -50668,6 +52483,174 @@ proc: BEGIN INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded FROM ticket WHERE id = vTicketFk; + + CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, TRUE); + + CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, + s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY s.itemFk; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + + IF vLanded IS NULL THEN + + CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + UPDATE vn2008.Tickets t + SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) + WHERE Id_Ticket = vTicketFk; + + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + END IF; + + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.ticketComponentPrice; + DROP TEMPORARY TABLE tmp.ticketComponent; + DROP TEMPORARY TABLE tmp.sale; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_recalcComponentsForcePrice__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponentsForcePrice__`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN ) +proc: BEGIN + +/** + * Este procedimiento trata de "rebionizar" un ticket, + * eliminando los componentes existentes e insertandolos de nuevo + * + * @param vTicketFk Id del ticket + * @return tmp.buyUltimate + */ + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vLanded DATE; + DECLARE vZoneFk INTEGER; + + IF vIsTicketEditable IS NULL THEN + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + END IF; + SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM ticket + WHERE id = vTicketFk; + + CALL zone_getShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); + + CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, + s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY s.itemFk; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + + IF vLanded IS NULL THEN + + CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + UPDATE vn2008.Tickets t + SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) + WHERE Id_Ticket = vTicketFk; + + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + END IF; + + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.ticketComponentPrice; + DROP TEMPORARY TABLE tmp.ticketComponent; + DROP TEMPORARY TABLE tmp.sale; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_recalcComponents__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents__`(IN vTicketFk BIGINT ) +proc: BEGIN + +/** + * Este procedimiento trata de "rebionizar" un ticket, + * eliminando los componentes existentes e insertandolos de nuevo + * + * @param vTicketFk Id del ticket + * @return tmp.buyUltimate + */ + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vLanded DATE; + DECLARE vIsTicketEditable BOOLEAN; + DECLARE vZoneFk INTEGER; + + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + + SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM ticket + WHERE id = vTicketFk; CALL zone_getShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); @@ -50874,13 +52857,13 @@ BEGIN t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate) WHERE permissionRate <> 0; - UPDATE tmp.timeBusinessCalculate t - JOIN postgresql.calendar_labour cl ON cl.day = t.dated - JOIN postgresql.business_labour bl ON bl.business_id = t.businessFk AND bl.workcenter_id = cl.workcenter_id +UPDATE tmp.timeBusinessCalculate t + JOIN vn.calendarHolidays ch ON ch.dated = t.dated + JOIN postgresql.business_labour bl ON bl.business_id = t.businessFk AND bl.workcenter_id = ch.workcenterFk SET t.timeWorkSeconds = 0, t.timeWorkSexagesimal = 0, t.timeWorkDecimal = 0, - t.permissionRate = 1, + t.permissionrate = 1, t.type = 'Festivo' WHERE t.type IS NULL; @@ -50895,9 +52878,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -50915,7 +52898,7 @@ BEGIN SELECT userFk FROM vn.worker w JOIN vn.`user` u ON u.id = w.userFk - WHERE userFk IS NOT NULL AND u.active = TRUE; + WHERE userFk IS NOT NULL; CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); @@ -51787,9 +53770,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -51804,9 +53787,9 @@ BEGIN p.name, p.firstname, d.name AS department, - d.department_id as departmentFk, + d.id as departmentFk, b.date_start, - d.production, + d.isProduction, CAST(12 * blp.importepactado / clt.hours_week / 52 AS DECIMAL(10,2)) as costeHora FROM postgresql.person p @@ -51815,7 +53798,7 @@ BEGIN JOIN postgresql.business_labour bl ON bl.business_id = b.business_id JOIN postgresql.calendar_labour_type clt ON clt.calendar_labour_type_id = bl.calendar_labour_type_id JOIN postgresql.business_labour_payroll blp ON blp.business_id = b.business_id - JOIN vn2008.department d ON d.department_id = bl.department_id + JOIN vn.department d ON d.id = bl.department_id JOIN vn.worker w ON w.id = p.id_trabajador WHERE b.date_start <= vDate AND IFNULL(b.date_end,'3000-01-01') > vDate ; @@ -51832,16 +53815,16 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerDisable`(vUserId int) mainLabel:BEGIN - IF vUserId = 14255 THEN + IF (SELECT COUNT(*) FROM workerDisableExcluded WHERE workerFk = vUserId AND (dated > CURDATE() OR dated IS NULL)) > 0 THEN LEAVE mainLabel; END IF; DELETE FROM account.account @@ -51915,6 +53898,42 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerDisable__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `workerDisable__`(vUserId int) +mainLabel:BEGIN + + IF vUserId = 14255 THEN + LEAVE mainLabel; + END IF; + DELETE FROM account.account + WHERE id = vUserId; + + UPDATE account.user + SET role = 2 + WHERE id = vUserId; + + DELETE FROM pbx.sip + WHERE user_id = vUserId; + + UPDATE `client` c + JOIN payMethod p ON p.name = 'CONTADO' + SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE + WHERE c.id = vUserId; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `workerForAllCalculateBoss` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51965,9 +53984,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -52169,9 +54188,9 @@ BEGIN -- Festivos por centro de trabajo - UPDATE vn.workerJourney wj - JOIN postgresql.calendar_labour pcl ON pcl.day = wj.dated - JOIN postgresql.business_labour pbl ON wj.businessFk = pbl.business_id AND pbl.workcenter_id = pcl.workcenter_id +UPDATE vn.workerJourney wj + JOIN vn.calendarHolidays ch ON ch.dated = wj.dated + JOIN postgresql.business_labour pbl ON wj.businessFk = pbl.business_id AND pbl.workcenter_id = ch.workcenterFk SET wj.hollyday = wj.total, wj.permission = wj.contractJourney, wj.contractJourney = 0 @@ -52697,190 +54716,6 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_check`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100)) proc: BEGIN -/** - * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a vn.workerTimeControlAdd - * - * @param vUserFk Identificador del trabajador - * @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ; - * En caso de tener algun problema retorna el primero que encuentra - */ - DECLARE vLastIn DATETIME ; - DECLARE vLastOut DATETIME ; - DECLARE vDayWorkMax INT; - DECLARE vDayBreak INT; - DECLARE vWeekBreak INT ; - DECLARE vWeekScope INT; - DECLARE vDayStayMax INT; - DECLARE vProblem VARCHAR(20) DEFAULT NULL; - DECLARE vTimedWorked INT; - DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL; - DECLARE vTo VARCHAR(50) DEFAULT NULL; - DECLARE vUserName VARCHAR(50) DEFAULT NULL; - DECLARE vBody VARCHAR(255) DEFAULT NULL; - - SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax - INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax - FROM vn.workerTimeControlParams; - - SELECT MAX(timed) INTO vLastIn - FROM vn.workerTimeControl - WHERE userFk = vUserFk - AND direction = 'in'; - - SELECT MAX(timed) INTO vLastOut - FROM vn.workerTimeControl - WHERE userFk = vUserFk - AND direction = 'out'; - - SELECT email INTO vTo - FROM vn.worker w - WHERE w.id = (SELECT bossFk FROM vn.worker WHERE id = vUserFk); - - SELECT CONCAT(firstName,' ',lastName) INTO vUserName - FROM vn.worker w - WHERE w.id = vUserFk; - - - IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA - - -- VERIFICAR DESCANSO DIARIO - IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN - SELECT "Descansos 12 h" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ - IF (SELECT MOD(COUNT(*),2) -- <>0 - FROM vn.workerTimeControl - WHERE userFk = vUserFk - AND timed >= vLastIn - ) THEN - SELECT "Dias con fichadas impares" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - -- VERIFICAR VACACIONES - SELECT cs.type INTO vCalendarStateType - FROM postgresql.calendar_employee ce - JOIN postgresql.business b USING(business_id) - JOIN postgresql.profile pr ON pr.profile_id = b.client_id - JOIN postgresql.person p ON p.person_id = pr.person_id - JOIN postgresql.calendar_state cs USING(calendar_state_id) - JOIN vn.worker w ON w.id = p.id_trabajador - WHERE ce.date = CURDATE() - AND cs.isAllowedToWork = FALSE - AND w.userFk = vUserFk - LIMIT 1; - - IF(LENGTH(vCalendarStateType)) THEN - SELECT vCalendarStateType AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - - END IF; - - - -- VERIFICAR CONTRATO EN VIGOR - IF (SELECT COUNT(*) - FROM postgresql.business b - JOIN postgresql.profile pr ON pr.profile_id = b.client_id - JOIN postgresql.person p ON p.person_id = pr.person_id - JOIN vn.worker w ON w.id = p.id_trabajador - WHERE w.userFk = vUserFk - AND b.date_start <= vDated - AND IFNULL(b.date_end,vDated) >= vDated - ) = 0 THEN - SELECT "No hay un contrato en vigor" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - - END IF; - - -- VERIFICAR DESCANSO SEMANAL - SET @vHasBreakWeek:= FALSE; - SET @vLastTimed:= UNIX_TIMESTAMP((NOW() - INTERVAL vWeekScope SECOND)); - - DROP TEMPORARY TABLE IF EXISTS tmp.trash; - CREATE TEMPORARY TABLE tmp.trash - SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, - @vLastTimed:= UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed>= (NOW() - INTERVAL vWeekScope SECOND) - AND userFk= vUserFk - AND direction IN ('in','out') - ORDER BY timed ASC; - - IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA - SELECT "Descansos 36 h" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - DROP TEMPORARY TABLE tmp.trash; - - ELSE -- DIA ACTUAL - - -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO - SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(NOW()), 0) INTO vTimedWorked - FROM vn.workerTimeControl wtc - WHERE userFk = vUserFk - AND timed >= vLastIn - ORDER BY timed; - - IF vTimedWorked > vDayWorkMax THEN - SELECT "Jornadas" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - END IF; - - -- VERIFICAR DEPARTAMENTO - IF vTabletFk IS NOT NULL THEN - IF ( SELECT COUNT(*) - FROM vn.tabletDepartment td - JOIN vn.workerTimeControlUserInfo wtcu ON wtcu.departmentFk = td.departmentFk - WHERE td.tabletFk = vTabletFk AND wtcu.userFk = vUserFk - ) = 0 THEN - SELECT "No perteneces a este departamento." AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_check_` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_check_`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100)) -proc: BEGIN /** * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a vn.workerTimeControlAdd * @@ -53057,6 +54892,197 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_checkTest` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_checkTest`(vUserFk INT, vTabletFk VARCHAR(100), vTimed DATETIME) +BEGIN + +/** + * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a vn.workerTimeControlAdd + * @param vUserFk Identificador del trabajador + * @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ; + * En caso de tener algun problema retorna el primero que encuentra + */ + DECLARE vLastIn DATETIME ; + DECLARE vLastOut DATETIME ; + DECLARE vDayWorkMax INT; + DECLARE vDayBreak INT; + DECLARE vWeekBreak INT ; + DECLARE vWeekMaxBreak INT; + DECLARE vWeekScope INT; + DECLARE vWeekMaxScope INT; + DECLARE vDayStayMax INT; + DECLARE vAskInOut INT; + DECLARE vTimedWorked INT; + DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL; + DECLARE vDepartmentFk INT; + DECLARE vTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; + DECLARE vBody VARCHAR(255) DEFAULT NULL; + + IF (vTimed IS NULL) THEN + SET vTimed = NOW(); + END IF; + + SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax, weekMaxBreak, weekMaxScope, askInOut + INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax, vWeekMaxBreak, vWeekMaxScope, vAskInOut + FROM vn.workerTimeControlParams; + + SELECT MAX(timed) INTO vLastIn + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND + direction = 'in'; + + SELECT MAX(timed) INTO vLastOut + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND + direction = 'out'; + + SELECT email INTO vTo + FROM vn.worker w + WHERE w.id = (SELECT bossFk FROM vn.worker WHERE id = vUserFk); + + SELECT CONCAT(firstName,' ',lastName) INTO vUserName + FROM vn.worker w + WHERE w.id = vUserFk; + + -- VERIFICAR CONTRATO EN VIGOR + IF (SELECT COUNT(*) + FROM postgresql.business b + JOIN postgresql.profile pr ON pr.profile_id = b.client_id + JOIN postgresql.person p ON p.person_id = pr.person_id + JOIN vn.worker w ON w.id = p.id_trabajador + WHERE w.userFk = vUserFk AND + b.date_start <= CURDATE() AND + IFNULL(b.date_end,CURDATE()) >= CURDATE() + ) = 0 THEN + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + CALL util.throw("No hay un contrato en vigor"); + END IF; + + -- VERIFICAR DEPARTAMENTO + IF vTabletFk IS NOT NULL THEN + IF ( SELECT COUNT(*) + FROM vn.tabletDepartment td + JOIN vn.workerTimeControlUserInfo wtcu ON wtcu.departmentFk = td.departmentFk + WHERE td.tabletFk = vTabletFk AND wtcu.userFk = vUserFk + ) = 0 THEN + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + CALL util.throw("No perteneces a este departamento."); + END IF; + END IF; + + SELECT IFNULL(dayBreak, vDayBreak) INTO vDayBreak + FROM postgresql.business b + JOIN postgresql.profile pr ON pr.profile_id = b.client_id + JOIN postgresql.person p ON p.person_id = pr.person_id + JOIN postgresql. business_labour bl ON b.business_id = bl.business_id + JOIN postgresql.professional_category pc ON bl.professional_category_id = pc.professional_category_id + WHERE p.id_trabajador = vUserFk AND + b.date_start <= DATE(vTimed) AND + IFNULL(b.date_end, DATE(vTimed)) >= DATE(vTimed); + -- VERIFICAR DESCANSO DIARIO + -- 12 / 9 horas dependiendo del valor de vDayBreak + IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos ", FORMAT(vDayBreak/3600,0) ," h") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + CALL util.throw(CONCAT("Descansos ", FORMAT(vDayBreak/3600,0) ," h")); + END IF; + + -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ + IF (SELECT MOD(COUNT(*),2) -- <>0 + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND + timed >= vLastIn + ) THEN + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + CALL util.throw("Dias con fichadas impares"); + END IF; + -- VERIFICAR VACACIONES + SELECT cs.type INTO vCalendarStateType + FROM postgresql.calendar_employee ce + JOIN postgresql.business b USING(business_id) + JOIN postgresql.profile pr ON pr.profile_id = b.client_id + JOIN postgresql.person p ON p.person_id = pr.person_id + JOIN postgresql.calendar_state cs USING(calendar_state_id) + JOIN vn.worker w ON w.id = p.id_trabajador + WHERE ce.date = CURDATE() AND + cs.isAllowedToWork = FALSE AND + w.userFk = vUserFk + LIMIT 1; + + IF(LENGTH(vCalendarStateType)) THEN + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + CALL util.throw(vCalendarStateType); + END IF; + + -- VERIFICAR DESCANSO SEMANAL + SET @vHasBreakWeek:= FALSE; + SET @vLastTimed:= UNIX_TIMESTAMP((vTimed - INTERVAL vWeekScope SECOND)); + + DROP TEMPORARY TABLE IF EXISTS tmp.trash; + CREATE TEMPORARY TABLE tmp.trash + SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, + @vLastTimed:= UNIX_TIMESTAMP(timed) + FROM workerTimeControl + WHERE timed>= (vTimed - INTERVAL vWeekScope SECOND) AND + userFk= vUserFk AND + direction IN ('in','out') + ORDER BY timed ASC; + + IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA + SET @vHasBreakWeek:= FALSE; + SET @vLastTimed:= UNIX_TIMESTAMP((vTimed - INTERVAL vWeekMaxScope SECOND)); + DROP TEMPORARY TABLE tmp.trash; + CREATE TEMPORARY TABLE tmp.trash + SELECT IF(vWeekMaxBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, + @vLastTimed:= UNIX_TIMESTAMP(timed) + FROM workerTimeControl + WHERE timed>= (vTimed - INTERVAL vWeekMaxScope SECOND) AND + userFk= vUserFk AND + direction IN ('in','out') + ORDER BY timed ASC; + IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) < vWeekMaxBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos ", FORMAT(vWeekMaxBreak/3600,0) ," h") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + CALL util.throw(CONCAT( "Descansos ", FORMAT(vWeekMaxBreak/3600,0) ," h")); + END IF; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos ", FORMAT(vWeekBreak/3600,0) ," h") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + CALL util.warn(CONCAT( "Descansos ", FORMAT(vWeekBreak/3600,0) ," h")); + END IF; + DROP TEMPORARY TABLE tmp.trash; + + -- Preguntar dirección de la fichada + IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastIn) >= vAskInOut AND (SELECT MOD(COUNT(*),2) + FROM vn.workerTimeControl WHERE userFk = vUserFk AND timed >= vLastIn) THEN + CALL util.warn("AskInOut"); + END IF ; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_remove` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -55028,6 +57054,56 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getShipped` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vShowExpiredZones BOOLEAN) +BEGIN +/** + * Devuelve la mínima fecha de envío para cada warehouse + * + * @param vLanded La fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.zoneGetShipped + */ + CALL zone_getFromGeo(address_getGeo(vAddressFk)); + CALL zone_getOptionsForLanding(vLanded, vShowExpiredZones); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; + CREATE TEMPORARY TABLE tmp.zoneGetShipped + ENGINE = MEMORY + SELECT * FROM ( + SELECT zo.zoneFk, + TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, + zo.`hour`, + zw.warehouseFk, + z.agencyModeFk, + zo.price, + zo.bonus + FROM tmp.zoneOption zo + JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk + JOIN zone z ON z.id = zo.zoneFk + WHERE z.agencyModeFk = vAgencyModeFk + ORDER BY shipped) t + GROUP BY warehouseFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `zone_getShippedWarehouse` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -55040,6 +57116,34 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) BEGIN +/** + * Devuelve la mínima fecha de envío para cada warehouse + * + * @param vLanded La fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.zoneGetShipped + */ + + CALL zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, TRUE); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getShippedWarehouse__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse__`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) +BEGIN /** * Devuelve la mínima fecha de envío para cada warehouse * @@ -56547,6 +58651,24 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `expeditionTimeExpended` +-- + +/*!50001 DROP VIEW IF EXISTS `expeditionTimeExpended`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `expeditionTimeExpended` AS select `e`.`ticketFk` AS `ticketFk`,min(`e`.`created`) AS `started`,max(`e`.`created`) AS `finished`,max(`e`.`counter`) AS `cajas`,`w`.`code` AS `code`,`t`.`warehouseFk` AS `warehouseFk` from ((`expedition` `e` join `worker` `w` on((`w`.`id` = `e`.`workerFk`))) join `ticket` `t` on((`t`.`id` = `e`.`ticketFk`))) where (`e`.`created` > curdate()) group by `e`.`ticketFk` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `firstTicketShipped` -- @@ -57177,24 +59299,6 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Final view structure for view `saleVolume__` --- - -/*!50001 DROP VIEW IF EXISTS `saleVolume__`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `saleVolume__` AS select `s`.`ticketFk` AS `ticketFk`,`s`.`id` AS `saleFk`,ifnull(round(((((`i`.`compression` * (greatest(`i`.`density`,167) / 167)) * `ic`.`cm3`) * `s`.`quantity`) / 1000),2),0) AS `litros`,`t`.`routeFk` AS `routeFk`,`t`.`shipped` AS `shipped`,(((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) / 1000000) AS `volume`,((((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) * (greatest(`i`.`density`,167) / 167)) / 1000000) AS `physicalWeight`,(((`s`.`quantity` * `ic`.`cm3`) * `i`.`density`) / 1000000) AS `weight`,(((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) / 1000000) AS `physicalVolume`,((((`s`.`quantity` * `ic`.`cm3`) * `t`.`zonePrice`) * `i`.`compression`) / `cb`.`volume`) AS `freight` from ((((`sale` `s` join `item` `i` on((`i`.`id` = `s`.`itemFk`))) join `ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `packaging` `cb` on((`cb`.`id` = '94'))) join `itemCost` `ic` on(((`ic`.`itemFk` = `s`.`itemFk`) and (`ic`.`warehouseFk` = `t`.`warehouseFk`)))) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - -- -- Final view structure for view `sale_freightComponent` -- @@ -57213,6 +59317,42 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `salesPreparedLastHour` +-- + +/*!50001 DROP VIEW IF EXISTS `salesPreparedLastHour`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `salesPreparedLastHour` AS select `t`.`warehouseFk` AS `warehouseFk`,`st`.`saleFk` AS `saleFk`,`st`.`isChecked` AS `isChecked`,`st`.`originalQuantity` AS `originalQuantity`,`a`.`accion` AS `accion`,`st`.`created` AS `created`,`e`.`code` AS `code`,`w`.`firstName` AS `firstname`,`w`.`lastName` AS `lastName`,`w`.`code` AS `workerCode`,((`r`.`cm3` * `s`.`quantity`) / 1000) AS `litros`,`s`.`concept` AS `concept`,`d`.`name` AS `departmentName` from (((((((((`vn`.`saleTracking` `st` left join `vn`.`salesPreviousPreparated` `prevPrepSales` on((`prevPrepSales`.`saleFk` = `st`.`saleFk`))) join `vn`.`sale` `s` on((`s`.`id` = `st`.`saleFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `bi`.`rotacion` `r` on(((`r`.`warehouse_id` = `t`.`warehouseFk`) and (`r`.`Id_Article` = `s`.`itemFk`)))) join `vn`.`worker` `w` on((`w`.`id` = `st`.`workerFk`))) join `vn`.`state` `e` on((`e`.`id` = `st`.`stateFk`))) join `vncontrol`.`accion` `a` on((`a`.`accion_id` = `st`.`actionFk`))) join `vn`.`workerDepartment` `wd` on((`wd`.`workerFk` = `st`.`workerFk`))) join `vn`.`department` `d` on((`d`.`id` = `wd`.`departmentFk`))) where ((`st`.`created` > (now() + interval -(1) hour)) and isnull(`prevPrepSales`.`saleFk`) and (not((`d`.`name` like 'EQUIPO%')))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `salesPreviousPreparated` +-- + +/*!50001 DROP VIEW IF EXISTS `salesPreviousPreparated`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `salesPreviousPreparated` AS select `st`.`saleFk` AS `saleFk` from (`saleTracking` `st` join `state` `e` on((`e`.`id` = `st`.`stateFk`))) where ((`st`.`created` > curdate()) and (`e`.`code` like 'PREVIOUS_PREPARATION')) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `supplierPackaging` -- @@ -57465,6 +59605,42 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `workerSpeedExpedition` +-- + +/*!50001 DROP VIEW IF EXISTS `workerSpeedExpedition`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerSpeedExpedition` AS select `sv`.`ticketFk` AS `ticketFk`,sum(`sv`.`litros`) AS `litros`,sum(if((`sub`.`started` > (now() + interval -(1) hour)),`sv`.`litros`,0)) AS `literLastHour`,cast(((60 * sum(`sv`.`litros`)) / time_to_sec(timediff(max(`sub`.`finished`),min(`sub`.`started`)))) as decimal(10,1)) AS `litersByMinute`,`sub`.`code` AS `workerCode`,`sub`.`cajas` AS `cajas`,`sub`.`warehouseFk` AS `warehouseFk` from (`saleVolume` `sv` join `expeditionTimeExpended` `sub` on((`sub`.`ticketFk` = `sv`.`ticketFk`))) group by `workerCode` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `workerSpeedSaleTracking` +-- + +/*!50001 DROP VIEW IF EXISTS `workerSpeedSaleTracking`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerSpeedSaleTracking` AS select `salesPreparedLastHour`.`warehouseFk` AS `warehouseFk`,`salesPreparedLastHour`.`accion` AS `accion`,`salesPreparedLastHour`.`workerCode` AS `workerCode`,sum(`salesPreparedLastHour`.`litros`) AS `sumaLitros`,min(`salesPreparedLastHour`.`created`) AS `started`,max(`salesPreparedLastHour`.`created`) AS `finished`,sum(if((`salesPreparedLastHour`.`created` >= (now() + interval -(1) hour)),`salesPreparedLastHour`.`litros`,0)) AS `sumaLitrosLastHour`,cast(((60 * sum(`salesPreparedLastHour`.`litros`)) / time_to_sec(timediff(max(`salesPreparedLastHour`.`created`),min(`salesPreparedLastHour`.`created`)))) as decimal(10,1)) AS `litersByMinute`,`salesPreparedLastHour`.`departmentName` AS `departmentName` from `vn`.`salesPreparedLastHour` group by `salesPreparedLastHour`.`warehouseFk`,`salesPreparedLastHour`.`accion`,`salesPreparedLastHour`.`workerCode` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `workerTeamCollegues` -- @@ -57588,4 +59764,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-02-27 13:42:11 +-- Dump completed on 2020-03-16 9:43:30 From 219519dc267e420f8c8d283bbdf9c97977ccd14e Mon Sep 17 00:00:00 2001 From: Ainki Date: Mon, 30 Mar 2020 14:28:29 +0200 Subject: [PATCH 18/25] test, fitxures and changes --- db/dump/fixtures.sql | 25 +- db/dump/structure.sql | 2076 ++++++++++++++++++++--------------------- 2 files changed, 1062 insertions(+), 1039 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 7b2fd1cae..fbe33159a 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -21,7 +21,7 @@ INSERT INTO `vn`.`bionicConfig` (`generalInflationCoeficient`, `minimumDensityVo (1.30, 167.00, 138000, 71); INSERT INTO `vn`.`chatConfig` (`host`, `api`) - VALUES + VALUES ('https://chat.verdnatura.es', 'https://chat.verdnatura.es/api/v1'); INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`) @@ -954,6 +954,29 @@ INSERT INTO `vn`.`itemPlacement`(`id`, `itemFk`, `warehouseFk`, `code`) (3, 1, 3, 'A3'), (4, 2, 1, 'A4'); + +INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`) + VALUES + (1, 106, 5), + (2, 106, 14); + +INSERT INTO `vn`.`parking` (`column`, `row`, `sectorFk`, `code`, `pickingOrder`) + VALUES + ('100', '01', 1, '100-01', 1); + +INSERT INTO `vn`.`shelving` (`code`, `parkingFk`, `priority`, `userFk`) + VALUES + ('UXN', 1, 1, 106); + +INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `shelve`, `deep`, `quantity`, `visible`, `available`, `grouping`, `packing`, `level`, `userFk`) + VALUES + (1, 'UXN', 'A', 2, 12, 12, 12, 12, 12, 1, 106); + +INSERT INTO `vn`.`ticketCollection` (`ticketFk`, `collectionFk`, `level`) + VALUES + (1, 1, 1); + + INSERT INTO `edi`.`genus`(`genus_id`, `latin_genus_name`, `entry_date`, `expiry_date`, `change_date_time`) VALUES (1, 'Abelia' , CURDATE(), NULL, CURDATE()), diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 8e783c833..2a1a168d7 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -4055,16 +4055,16 @@ BEGIN * La tabla mana_spellers es una caché * */ - - UPDATE mana_spellers me - JOIN - (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual - FROM bs.vendedores - WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) - GROUP BY Id_Trabajador - ) lastYearSales USING(Id_Trabajador) - SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; - + + UPDATE mana_spellers me + JOIN + (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual + FROM bs.vendedores + WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) + GROUP BY Id_Trabajador + ) lastYearSales USING(Id_Trabajador) + SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6703,9 +6703,9 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cacheCalc_clean`() -BEGIN - DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); - DELETE FROM cache_calc WHERE expires < vCleanTime; +BEGIN + DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); + DELETE FROM cache_calc WHERE expires < vCleanTime; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6723,27 +6723,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` 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 */ ; @@ -6761,88 +6761,88 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` 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 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 - INTO v_cache_id, v_calc, v_expires - 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 - 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 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 + INTO v_cache_id, v_calc, v_expires + 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 + 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 */ ; @@ -6860,24 +6860,24 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_unlock`(IN `v_calc` INT) -proc: BEGIN - DECLARE v_cache_name VARCHAR(50); - DECLARE v_params VARCHAR(100); - - IF v_calc IS NULL THEN - LEAVE proc; - END IF; - - 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; - - DELETE FROM cache_calc WHERE id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +proc: BEGIN + DECLARE v_cache_name VARCHAR(50); + DECLARE v_params VARCHAR(100); + + IF v_calc IS NULL THEN + LEAVE proc; + END IF; + + 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; + + DELETE FROM cache_calc WHERE 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 */ ; @@ -6896,9 +6896,9 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_clean`() NO SQL -BEGIN - CALL available_clean; - CALL visible_clean; +BEGIN + CALL available_clean; + CALL visible_clean; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6916,13 +6916,13 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - - DECLARE vDateShort DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); - - DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; +BEGIN + + DECLARE vDateShort DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); + + DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8386,158 +8386,158 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT) -BEGIN - DECLARE vRef INT; - DECLARE vBuy INT; - DECLARE vItem INT; - DECLARE vQty INT; - DECLARE vPackage INT; - DECLARE vIsLot BOOLEAN; - DECLARE vForceToPacking INT DEFAULT 2; - - -- Carga los datos necesarios del EKT - - SELECT ref, qty, package INTO vRef, vQty, vPackage - FROM ekt e - LEFT JOIN item i ON e.ref = i.id - WHERE e.id = vSelf; - - -- Inserta el cubo si no existe - - IF vPackage = 800 - THEN - SET vPackage = 800 + vQty; - - INSERT IGNORE INTO vn2008.Cubos SET - Id_Cubo = vPackage, - x = 7200 / vQty, - y = 1; - ELSE - INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) - SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) - FROM bucket WHERE bucket_id = vPackage; - - IF ROW_COUNT() > 0 - THEN - INSERT INTO vn2008.mail SET - `subject` = 'Cubo añadido', - `text` = CONCAT('Se ha añadido el cubo: ', vPackage), - `to` = 'ekt@verdnatura.es'; - END IF; - END IF; - - -- Intenta obtener el artículo en base a los atributos holandeses - - INSERT IGNORE INTO item_track SET - item_id = vRef; - - SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem - FROM vn2008.buy_edi e - JOIN item_track t ON t.item_id = e.ref - LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref - LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id - JOIN vn2008.config cfg - WHERE e.id = vSelf - AND l.id != vSelf - AND c.Id_Article != cfg.generic_item - AND IF(t.s1, l.s1 = e.s1, TRUE) - AND IF(t.s2, l.s2 = e.s2, TRUE) - AND IF(t.s3, l.s3 = e.s3, TRUE) - AND IF(t.s4, l.s4 = e.s4, TRUE) - AND IF(t.s5, l.s5 = e.s5, TRUE) - AND IF(t.s6, l.s6 = e.s6, TRUE) - AND IF(t.kop, l.kop = e.kop, TRUE) - AND IF(t.pac, l.pac = e.pac, TRUE) - AND IF(t.cat, l.cat = e.cat, TRUE) - AND IF(t.ori, l.ori = e.ori, TRUE) - AND IF(t.pro, l.pro = e.pro, TRUE) - AND IF(t.sub, l.sub = e.sub, TRUE) - AND IF(t.package, l.package = e.package, TRUE) - AND c.Id_Article < 170000 - ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; - - -- Determina si el articulo se vende por lotes - - IF vItem - THEN - SELECT COUNT(*) > 0 INTO vIsLot - FROM vn2008.Articles a - LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - WHERE a.Id_Article = vItem - AND t.`transaction`; - - -- Si el articulo se vende por lotes se inserta un nuevo artículo - - IF vIsLot - THEN - INSERT INTO vn2008.Articles ( - Article - ,Medida - ,Categoria - ,Id_Origen - ,iva_group_id - ,Foto - ,Color - ,Codintrastat - ,tipo_id - ,Tallos - ) - SELECT - i.`name` - ,IFNULL(e.s1, e.pac) - ,e.cat - ,IFNULL(o.id, 17) - ,IFNULL(a.iva_group_id, 1) - ,a.Foto - ,a.Color - ,a.Codintrastat - ,IFNULL(a.tipo_id, 10) - ,IF(a.tipo_id = 15, 0, 1) - FROM vn2008.buy_edi e - LEFT JOIN item i ON i.id = e.ref - LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori - LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem - WHERE e.id = vSelf; - - SET vItem = LAST_INSERT_ID(); - END IF; - END IF; - - -- Inserta la compra asociada al EKT - - INSERT INTO vn2008.Compres - ( - Id_Entrada - ,buy_edi_id - ,Costefijo - ,Id_Article - ,`grouping` - ,caja - ,Packing - ,Cantidad - ,Productor - ,Etiquetas - ,Id_Cubo - ) - SELECT - cfg.edi_entry - ,vSelf - ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri - ,IFNULL(vItem, cfg.generic_item) - ,IFNULL(c.`grouping`, e.pac) - ,vForceToPacking - ,@pac := e.pac / @t - ,@pac * e.qty - ,s.company_name - ,e.qty - ,IFNULL(c.Id_Cubo, e.package) - FROM vn2008.buy_edi e - LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy - LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article - LEFT JOIN supplier s ON e.pro = s.supplier_id - JOIN vn2008.config cfg - WHERE e.id = vSelf - LIMIT 1; +BEGIN + DECLARE vRef INT; + DECLARE vBuy INT; + DECLARE vItem INT; + DECLARE vQty INT; + DECLARE vPackage INT; + DECLARE vIsLot BOOLEAN; + DECLARE vForceToPacking INT DEFAULT 2; + + -- Carga los datos necesarios del EKT + + SELECT ref, qty, package INTO vRef, vQty, vPackage + FROM ekt e + LEFT JOIN item i ON e.ref = i.id + WHERE e.id = vSelf; + + -- Inserta el cubo si no existe + + IF vPackage = 800 + THEN + SET vPackage = 800 + vQty; + + INSERT IGNORE INTO vn2008.Cubos SET + Id_Cubo = vPackage, + x = 7200 / vQty, + y = 1; + ELSE + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) + SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) + FROM bucket WHERE bucket_id = vPackage; + + IF ROW_COUNT() > 0 + THEN + INSERT INTO vn2008.mail SET + `subject` = 'Cubo añadido', + `text` = CONCAT('Se ha añadido el cubo: ', vPackage), + `to` = 'ekt@verdnatura.es'; + END IF; + END IF; + + -- Intenta obtener el artículo en base a los atributos holandeses + + INSERT IGNORE INTO item_track SET + item_id = vRef; + + SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem + FROM vn2008.buy_edi e + JOIN item_track t ON t.item_id = e.ref + LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref + LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id + JOIN vn2008.config cfg + WHERE e.id = vSelf + AND l.id != vSelf + AND c.Id_Article != cfg.generic_item + AND IF(t.s1, l.s1 = e.s1, TRUE) + AND IF(t.s2, l.s2 = e.s2, TRUE) + AND IF(t.s3, l.s3 = e.s3, TRUE) + AND IF(t.s4, l.s4 = e.s4, TRUE) + AND IF(t.s5, l.s5 = e.s5, TRUE) + AND IF(t.s6, l.s6 = e.s6, TRUE) + AND IF(t.kop, l.kop = e.kop, TRUE) + AND IF(t.pac, l.pac = e.pac, TRUE) + AND IF(t.cat, l.cat = e.cat, TRUE) + AND IF(t.ori, l.ori = e.ori, TRUE) + AND IF(t.pro, l.pro = e.pro, TRUE) + AND IF(t.sub, l.sub = e.sub, TRUE) + AND IF(t.package, l.package = e.package, TRUE) + AND c.Id_Article < 170000 + ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; + + -- Determina si el articulo se vende por lotes + + IF vItem + THEN + SELECT COUNT(*) > 0 INTO vIsLot + FROM vn2008.Articles a + LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id + WHERE a.Id_Article = vItem + AND t.`transaction`; + + -- Si el articulo se vende por lotes se inserta un nuevo artículo + + IF vIsLot + THEN + INSERT INTO vn2008.Articles ( + Article + ,Medida + ,Categoria + ,Id_Origen + ,iva_group_id + ,Foto + ,Color + ,Codintrastat + ,tipo_id + ,Tallos + ) + SELECT + i.`name` + ,IFNULL(e.s1, e.pac) + ,e.cat + ,IFNULL(o.id, 17) + ,IFNULL(a.iva_group_id, 1) + ,a.Foto + ,a.Color + ,a.Codintrastat + ,IFNULL(a.tipo_id, 10) + ,IF(a.tipo_id = 15, 0, 1) + FROM vn2008.buy_edi e + LEFT JOIN item i ON i.id = e.ref + LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori + LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem + WHERE e.id = vSelf; + + SET vItem = LAST_INSERT_ID(); + END IF; + END IF; + + -- Inserta la compra asociada al EKT + + INSERT INTO vn2008.Compres + ( + Id_Entrada + ,buy_edi_id + ,Costefijo + ,Id_Article + ,`grouping` + ,caja + ,Packing + ,Cantidad + ,Productor + ,Etiquetas + ,Id_Cubo + ) + SELECT + cfg.edi_entry + ,vSelf + ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri + ,IFNULL(vItem, cfg.generic_item) + ,IFNULL(c.`grouping`, e.pac) + ,vForceToPacking + ,@pac := e.pac / @t + ,@pac * e.qty + ,s.company_name + ,e.qty + ,IFNULL(c.Id_Cubo, e.package) + FROM vn2008.buy_edi e + LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy + LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article + LEFT JOIN supplier s ON e.pro = s.supplier_id + JOIN vn2008.config cfg + WHERE e.id = vSelf + LIMIT 1; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8587,154 +8587,154 @@ CREATE DEFINER=`root`@`%` PROCEDURE `exchange_new`( IN `vAuction` SMALLINT, IN `vPackage` INT, IN `vPutOrderFk` INT) -BEGIN +BEGIN /** * Adds a new exchange, generates it's barcode and * inserts/updates the transaction. When the referenced * transaction exists as provisional, updates it with - * the new values. - */ - DECLARE vEkt INT; - DECLARE vRewriteKop INT DEFAULT NULL; - DECLARE vBarcode CHAR(15) DEFAULT NULL; - DECLARE vIsDuplicated BOOL; + * the new values. + */ + DECLARE vEkt INT; + DECLARE vRewriteKop INT DEFAULT NULL; + DECLARE vBarcode CHAR(15) DEFAULT NULL; + DECLARE vIsDuplicated BOOL; DECLARE vUpdateExistent BOOL DEFAULT FALSE; - DECLARE duplicateKey CONDITION FOR 1062; - - DECLARE CONTINUE HANDLER FOR duplicateKey - SET vIsDuplicated = TRUE; - - -- Generates the barcode - - IF vAgj != 0 AND vAgj IS NOT NULL - THEN - SET vBarcode = CONCAT( - LPAD(vAuction, 2, 0), - LPAD(IFNULL(vClock, 99), 2, 0), - LPAD(DAYOFYEAR(vDate), 3, 0), - IF(vClock IS NULL OR vClock = 99, - LPAD(vAgj, 7, 0), - CONCAT(LPAD(vAgj, 5, 0), '01') - ), - '0' - ); - END IF; - - -- Rewrites the kop parameter - - IF vKop IS NULL THEN - SELECT defaultKop INTO vKop FROM exchangeConfig; - END IF; - - SELECT e.kop INTO vRewriteKop - FROM mailSender e - JOIN mail m ON m.senderFk = e.id - WHERE m.id = vMailFk; - - SET vKop = IFNULL(vRewriteKop, vKop); - - -- Inserts the new transaction + DECLARE duplicateKey CONDITION FOR 1062; - SET vIsDuplicated = FALSE; - INSERT INTO ekt SET - barcode = IFNULL(vBarcode, barcode) - ,deliveryNumber = vDeliveryNumber - ,entryYear = YEAR(vDate) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk; - - -- If it exists duplicado updates it - - IF NOT vIsDuplicated - THEN - SET vEkt = LAST_INSERT_ID(); - CALL ekt_load (vEkt); - - ELSEIF vDeliveryNumber != 0 - AND vDeliveryNumber IS NOT NULL - THEN - SELECT id INTO vEkt - FROM ekt - WHERE deliveryNumber = vDeliveryNumber; - - SELECT COUNT(*) = 0 INTO vUpdateExistent - FROM ekt t - JOIN `exchange` b ON b.ektFk = t.id - JOIN exchangeConfig c - WHERE t.deliveryNumber = vDeliveryNumber - AND t.entryYear = YEAR(vDate) - AND b.typeFk != c.presaleFk; - END IF; - - IF vUpdateExistent - THEN - UPDATE ekt SET - barcode = IFNULL(vBarcode, barcode) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk - WHERE id = vEkt; - END IF; - - -- Registers the exchange - - INSERT INTO `exchange` SET - mailFk = vMailFk - ,typeFk = vType - ,ektFk = vEkt; + DECLARE CONTINUE HANDLER FOR duplicateKey + SET vIsDuplicated = TRUE; + + -- Generates the barcode + + IF vAgj != 0 AND vAgj IS NOT NULL + THEN + SET vBarcode = CONCAT( + LPAD(vAuction, 2, 0), + LPAD(IFNULL(vClock, 99), 2, 0), + LPAD(DAYOFYEAR(vDate), 3, 0), + IF(vClock IS NULL OR vClock = 99, + LPAD(vAgj, 7, 0), + CONCAT(LPAD(vAgj, 5, 0), '01') + ), + '0' + ); + END IF; + + -- Rewrites the kop parameter + + IF vKop IS NULL THEN + SELECT defaultKop INTO vKop FROM exchangeConfig; + END IF; + + SELECT e.kop INTO vRewriteKop + FROM mailSender e + JOIN mail m ON m.senderFk = e.id + WHERE m.id = vMailFk; + + SET vKop = IFNULL(vRewriteKop, vKop); + + -- Inserts the new transaction + + SET vIsDuplicated = FALSE; + INSERT INTO ekt SET + barcode = IFNULL(vBarcode, barcode) + ,deliveryNumber = vDeliveryNumber + ,entryYear = YEAR(vDate) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk; + + -- If it exists duplicado updates it + + IF NOT vIsDuplicated + THEN + SET vEkt = LAST_INSERT_ID(); + CALL ekt_load (vEkt); + + ELSEIF vDeliveryNumber != 0 + AND vDeliveryNumber IS NOT NULL + THEN + SELECT id INTO vEkt + FROM ekt + WHERE deliveryNumber = vDeliveryNumber; + + SELECT COUNT(*) = 0 INTO vUpdateExistent + FROM ekt t + JOIN `exchange` b ON b.ektFk = t.id + JOIN exchangeConfig c + WHERE t.deliveryNumber = vDeliveryNumber + AND t.entryYear = YEAR(vDate) + AND b.typeFk != c.presaleFk; + END IF; + + IF vUpdateExistent + THEN + UPDATE ekt SET + barcode = IFNULL(vBarcode, barcode) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk + WHERE id = vEkt; + END IF; + + -- Registers the exchange + + INSERT INTO `exchange` SET + mailFk = vMailFk + ,typeFk = vType + ,ektFk = vEkt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10810,30 +10810,30 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `item_listAllocation`(IN `vWh` TINYINT, IN `vDate` DATE, IN `vType` INT, IN `vPrefix` VARCHAR(255), IN `vUseIds` BOOLEAN) -BEGIN -/** - * Lists visible items and it's box sizes of the specified - * type at specified date. - * - * @param vWh The warehouse id - * @param vDate The visible date - * @param vType The type id - * @param vPrefix The article prefix to filter or %NULL for all - * @param vUseIds Whether to order the result by item id - * @select List of visible items with it's box sizes - */ - CALL item_getVisible(vWh, vDate, vType, vPrefix); - - IF vUseIds - THEN - SELECT * FROM tmp.itemVisible - ORDER BY Id_Article; - ELSE - SELECT * FROM tmp.itemVisible - ORDER BY Article, packing; - END IF; - - DROP TEMPORARY TABLE tmp.itemVisible; +BEGIN +/** + * Lists visible items and it's box sizes of the specified + * type at specified date. + * + * @param vWh The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @param vUseIds Whether to order the result by item id + * @select List of visible items with it's box sizes + */ + CALL item_getVisible(vWh, vDate, vType, vPrefix); + + IF vUseIds + THEN + SELECT * FROM tmp.itemVisible + ORDER BY Id_Article; + ELSE + SELECT * FROM tmp.itemVisible + ORDER BY Article, packing; + END IF; + + DROP TEMPORARY TABLE tmp.itemVisible; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -16189,8 +16189,8 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `log_add_beta`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) -proc: BEGIN - -- XXX: Disabled while testing +proc: BEGIN + -- XXX: Disabled while testing DECLARE vLanded DATE; DECLARE vWarehouseFk INT; DECLARE vBuyerFk INT; @@ -16198,20 +16198,20 @@ proc: BEGIN DECLARE vItemFk INT; DECLARE vItemName VARCHAR(50); - -- LEAVE proc; + -- LEAVE proc; - IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vOldId, - operation = 'delete'; - END IF; - - IF vNewId IS NOT NULL THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vNewId, - operation = 'insert'; + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vOldId, + operation = 'delete'; + END IF; + + IF vNewId IS NOT NULL THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vNewId, + operation = 'insert'; END IF; IF vTableName = 'buy' THEN @@ -16241,7 +16241,7 @@ proc: BEGIN END IF; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -16509,29 +16509,29 @@ CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshSale`( BEGIN DROP TEMPORARY TABLE IF EXISTS tValues; CREATE TEMPORARY TABLE tValues - ENGINE = MEMORY - SELECT - m.id saleFk, - m.ticketFk, - m.itemFk, - t.warehouseFk, - t.shipped, + ENGINE = MEMORY + SELECT + m.id saleFk, + m.ticketFk, + m.itemFk, + t.warehouseFk, + t.shipped, ABS(m.quantity) quantity, m.created, TIMESTAMPADD(DAY, tp.life, t.shipped) expired, m.quantity < 0 isIn, - m.isPicked OR s.alertLevel > 1 isPicked - FROM vn.sale m - JOIN vn.ticket t ON t.id = m.ticketFk + m.isPicked OR s.alertLevel > 1 isPicked + FROM vn.sale m + JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id JOIN vn.item i ON i.id = m.itemFk - JOIN vn.itemType tp ON tp.id = i.typeFk + JOIN vn.itemType tp ON tp.id = i.typeFk WHERE ( - vTableId IS NULL - OR (vTableName = 'ticket' AND t.id = vTableId) - OR (vTableName = 'sale' AND m.id = vTableId) - ) - AND t.shipped >= vn.getInventoryDate() + vTableId IS NULL + OR (vTableName = 'ticket' AND t.id = vTableId) + OR (vTableName = 'sale' AND m.id = vTableId) + ) + AND t.shipped >= vn.getInventoryDate() AND m.quantity != 0; REPLACE INTO inbound ( @@ -16564,7 +16564,7 @@ BEGIN FROM tValues WHERE !isIn; - DROP TEMPORARY TABLE tValues; + DROP TEMPORARY TABLE tValues; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29495,90 +29495,90 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN - - DECLARE vCurrentCount INT; - DECLARE vCheckSum INT; - DECLARE vIsAlreadyNotified BOOLEAN; - DECLARE vTableQueue TEXT; - DECLARE vLineQueue TEXT; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vCur CURSOR FOR - SELECT CONCAT(' - ', IFNULL(pq.id, ''), ' - ', IFNULL(p.path, ''),' - ', IFNULL(i.Informe, ''),' - ', IFNULL(e.Estado, ''),' - ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' - ', IFNULL(pq.`error`, ''),' - ') - FROM vn.printingQueue pq - LEFT JOIN vn.worker w ON w.id = pq.worker - LEFT JOIN vn.printer p ON p.id = pq.printer - LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report - JOIN vn2008.Estados e ON e.Id_Estado = pq.state - LIMIT 30; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum - FROM vn.printingQueue WHERE state = 1; - - SELECT isAlreadyNotified INTO vIsAlreadyNotified - FROM printingQueueCheck; - - IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND - (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND - vIsAlreadyNotified = FALSE AND vCurrentCount > 0 - THEN - - SELECT ' - - - - - - - - ' INTO vTableQueue; - - OPEN vCur; - - l: LOOP - - SET vDone = FALSE; - - FETCH vCur INTO vLineQueue; - - IF vDone THEN - LEAVE l; - END IF; - - SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; - - END LOOP; - - CLOSE vCur; - - INSERT INTO vn2008.mail (`to`, subject, text) - VALUES ('cau@verdnatura.es, sysadmin@verdnatura.es', - 'servidor de impresion parado', - CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); - - UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; - END IF; - - IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND - vIsAlreadyNotified = TRUE - THEN - UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; - END IF; - - UPDATE printingQueueCheck - SET lastCount = vCurrentCount, - lastCheckSum = vCheckSum; - +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN + + DECLARE vCurrentCount INT; + DECLARE vCheckSum INT; + DECLARE vIsAlreadyNotified BOOLEAN; + DECLARE vTableQueue TEXT; + DECLARE vLineQueue TEXT; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCur CURSOR FOR + SELECT CONCAT(' + ', IFNULL(pq.id, ''), ' + ', IFNULL(p.path, ''),' + ', IFNULL(i.Informe, ''),' + ', IFNULL(e.Estado, ''),' + ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' + ', IFNULL(pq.`error`, ''),' + ') + FROM vn.printingQueue pq + LEFT JOIN vn.worker w ON w.id = pq.worker + LEFT JOIN vn.printer p ON p.id = pq.printer + LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report + JOIN vn2008.Estados e ON e.Id_Estado = pq.state + LIMIT 30; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum + FROM vn.printingQueue WHERE state = 1; + + SELECT isAlreadyNotified INTO vIsAlreadyNotified + FROM printingQueueCheck; + + IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND + (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND + vIsAlreadyNotified = FALSE AND vCurrentCount > 0 + THEN + + SELECT ' + + + + + + + + ' INTO vTableQueue; + + OPEN vCur; + + l: LOOP + + SET vDone = FALSE; + + FETCH vCur INTO vLineQueue; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; + + END LOOP; + + CLOSE vCur; + + INSERT INTO vn2008.mail (`to`, subject, text) + VALUES ('cau@verdnatura.es, sysadmin@verdnatura.es', + 'servidor de impresion parado', + CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); + + UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; + END IF; + + IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND + vIsAlreadyNotified = TRUE + THEN + UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; + END IF; + + UPDATE printingQueueCheck + SET lastCount = vCurrentCount, + lastCheckSum = vCheckSum; + END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -35117,27 +35117,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean__`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE oneYearAgo DATE; - DECLARE twoYearsAgo DATE; - DECLARE fourYearsAgo DATE; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); - SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); - SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); - - DELETE FROM vn.message WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; - DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; - DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); - CALL shelving_clean; - +BEGIN + DECLARE vDateShort DATETIME; + DECLARE oneYearAgo DATE; + DECLARE twoYearsAgo DATE; + DECLARE fourYearsAgo DATE; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); + SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); + SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); + + DELETE FROM vn.message WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; + DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; + DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); + CALL shelving_clean; + CALL vn.ticketPackagingRecovery; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35980,54 +35980,54 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker__`() -BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vClientFk INT; - - DECLARE rs CURSOR FOR - SELECT c.clientFk - FROM tmp.clientGetDebt c - LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk - WHERE IFNULL(r.risk,0) = 0; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - SELECT cd.id as clientFk - FROM bs.clientDied cd - LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id - JOIN vn.client c ON c.id = cd.id - JOIN vn.province p ON p.id = c.provinceFk - JOIN vn.country co ON co.id = p.countryFk - WHERE cd.Aviso = 'TERCER AVISO' - AND cp.clientFk IS NULL - AND co.country NOT IN ('Portugal','Francia','España exento') - AND c.salesPersonFk IS NOT NULL; - - CALL vn.clientGetDebt(curdate()); - - DROP TEMPORARY TABLE IF EXISTS tmp.contador; - CREATE TEMPORARY TABLE tmp.contador (id INT) - ENGINE = MEMORY; - - OPEN rs; - FETCH rs INTO vClientFk; - - WHILE NOT done DO - INSERT INTO tmp.contador SET id = vClientFk; - CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vClientFk INT; + + DECLARE rs CURSOR FOR + SELECT c.clientFk + FROM tmp.clientGetDebt c + LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk + WHERE IFNULL(r.risk,0) = 0; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT cd.id as clientFk + FROM bs.clientDied cd + LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id + JOIN vn.client c ON c.id = cd.id + JOIN vn.province p ON p.id = c.provinceFk + JOIN vn.country co ON co.id = p.countryFk + WHERE cd.Aviso = 'TERCER AVISO' + AND cp.clientFk IS NULL + AND co.country NOT IN ('Portugal','Francia','España exento') + AND c.salesPersonFk IS NOT NULL; + + CALL vn.clientGetDebt(curdate()); + + DROP TEMPORARY TABLE IF EXISTS tmp.contador; + CREATE TEMPORARY TABLE tmp.contador (id INT) + ENGINE = MEMORY; + + OPEN rs; + FETCH rs INTO vClientFk; + + WHILE NOT done DO + INSERT INTO tmp.contador SET id = vClientFk; + CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; INSERT INTO vn.clientLog (originFk, userFk, `action`, description) VALUES (vClientFk, account.userGetId(), 'update', CONCAT('Se ha desasignado el cliente por que no ha comprado en 3 meses')); - + REPLACE bs.clientNewBorn(clientFk, shipped) - VALUES(vClientFk, CURDATE()); - FETCH rs INTO vClientFk; - END WHILE; - - CLOSE rs; + VALUES(vClientFk, CURDATE()); + FETCH rs INTO vClientFk; + END WHILE; + + CLOSE rs; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -38951,216 +38951,216 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryConverter`(IN `vEntry` INT) -BEGIN - - DECLARE vWarehouseIn INT; - DECLARE vWarehouseOut INT; - DECLARE vTravel INT; - - DECLARE done BOOL DEFAULT FALSE; - - DECLARE vId_Entrada INT; - DECLARE vId_Article INT; - DECLARE vEtiquetas INT; - DECLARE vId_Cubo VARCHAR(10); - DECLARE vPacking INT; - DECLARE vGrouping INT; - DECLARE vCantidad INT; - DECLARE vCostefijo DECIMAL(10,3); - DECLARE vPortefijo DECIMAL(10,3); - DECLARE vEmbalajefijo DECIMAL(10); - DECLARE vComisionfija DECIMAL(10,3); - DECLARE vCaja INT; - DECLARE vNicho VARCHAR(5); - DECLARE vTarifa1 DECIMAL(10,2); - DECLARE vTarifa2 DECIMAL(10,2); - DECLARE vTarifa3 DECIMAL(10,2); - DECLARE vPVP DECIMAL(10,2); - DECLARE vCompra INT; - - DECLARE rs CURSOR FOR - SELECT - b.Id_Entrada, - b.Id_Article, - b.Etiquetas, - b.Id_Cubo, - b.Packing, - b.`grouping`, - b.Cantidad, - b.Costefijo, - b.Portefijo, - b.Embalajefijo, - b.Comisionfija, - b.caja, - b.Nicho, - b.Tarifa1, - b.Tarifa2, - b.Tarifa3, - b.PVP - FROM vn2008.Compres b - JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article - WHERE Id_Entrada = vEntry; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT warehouseInFk, warehouseOutFk, tr.id - INTO vWarehouseIn, vWarehouseOut, vTravel - FROM travel tr - JOIN entry e ON e.travelFk = tr.id - WHERE e.id = vEntry; - - UPDATE travel - SET warehouseInFk = vWarehouseOut, - warehouseOutFk = vWarehouseIn - WHERE id = vTravel; - - UPDATE vn2008.Compres c - LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article - SET Etiquetas = 0, Cantidad = 0 - WHERE c.Id_Entrada = vEntry - AND ic.espItemFk IS NULL; - - OPEN rs; - - DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - WHILE NOT done DO - - -- Primero la linea original con las cantidades invertidas - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - VALUES - ( - vId_Entrada, - vId_Article, - - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP); - - -- Ahora la linea nueva, con el item genérico - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - SELECT - vId_Entrada, - genItemFk as Id_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP - FROM itemConversor - WHERE espItemFk = vId_Article; - - SELECT LAST_INSERT_ID() - INTO vCompra; - - REPLACE vn2008.Compres_mark(Id_Compra,`comment`) - SELECT vCompra, vId_Article; - - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - END WHILE; - - - CLOSE rs; - - - +BEGIN + + DECLARE vWarehouseIn INT; + DECLARE vWarehouseOut INT; + DECLARE vTravel INT; + + DECLARE done BOOL DEFAULT FALSE; + + DECLARE vId_Entrada INT; + DECLARE vId_Article INT; + DECLARE vEtiquetas INT; + DECLARE vId_Cubo VARCHAR(10); + DECLARE vPacking INT; + DECLARE vGrouping INT; + DECLARE vCantidad INT; + DECLARE vCostefijo DECIMAL(10,3); + DECLARE vPortefijo DECIMAL(10,3); + DECLARE vEmbalajefijo DECIMAL(10); + DECLARE vComisionfija DECIMAL(10,3); + DECLARE vCaja INT; + DECLARE vNicho VARCHAR(5); + DECLARE vTarifa1 DECIMAL(10,2); + DECLARE vTarifa2 DECIMAL(10,2); + DECLARE vTarifa3 DECIMAL(10,2); + DECLARE vPVP DECIMAL(10,2); + DECLARE vCompra INT; + + DECLARE rs CURSOR FOR + SELECT + b.Id_Entrada, + b.Id_Article, + b.Etiquetas, + b.Id_Cubo, + b.Packing, + b.`grouping`, + b.Cantidad, + b.Costefijo, + b.Portefijo, + b.Embalajefijo, + b.Comisionfija, + b.caja, + b.Nicho, + b.Tarifa1, + b.Tarifa2, + b.Tarifa3, + b.PVP + FROM vn2008.Compres b + JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article + WHERE Id_Entrada = vEntry; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SELECT warehouseInFk, warehouseOutFk, tr.id + INTO vWarehouseIn, vWarehouseOut, vTravel + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + WHERE e.id = vEntry; + + UPDATE travel + SET warehouseInFk = vWarehouseOut, + warehouseOutFk = vWarehouseIn + WHERE id = vTravel; + + UPDATE vn2008.Compres c + LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article + SET Etiquetas = 0, Cantidad = 0 + WHERE c.Id_Entrada = vEntry + AND ic.espItemFk IS NULL; + + OPEN rs; + + DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + WHILE NOT done DO + + -- Primero la linea original con las cantidades invertidas + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + VALUES + ( + vId_Entrada, + vId_Article, + - vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + - vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP); + + -- Ahora la linea nueva, con el item genérico + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + SELECT + vId_Entrada, + genItemFk as Id_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP + FROM itemConversor + WHERE espItemFk = vId_Article; + + SELECT LAST_INSERT_ID() + INTO vCompra; + + REPLACE vn2008.Compres_mark(Id_Compra,`comment`) + SELECT vCompra, vId_Article; + + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + END WHILE; + + + CLOSE rs; + + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39222,62 +39222,62 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryPrepare`(IN `idE` BIGINT) -BEGIN - SELECT - b.quantity / b.packing AS Paquetes, - b.packing AS `Grouping`, - barcode, - 'ASEGURADO' AS asegurado, - ic.name, - ic.order, - s.name AS Consignatario, - e.supplierFk AS Id_Cliente, - e.isOrdered, - e.isConfirmed, - 10 AS Calidad, - LPAD(IFNULL(cpd.id, ip.code), - 5, - '0') AS path, - b.entryFk AS Id_Ticket, - t.landed AS Fecha, - b.itemFk, - b.quantity, - i.name AS Concepte, - i.size, - i.inkFk, - i.category, - o.code AS Origen, - 0 AS Bultos, - wIn.`name` AS Tipo, - 0 AS OK, - 0 AS Reservado, - i.stems, - b.id AS Id_Movimiento, - ip.code, - 'PEDIDO ASEGURADO' AS MSG, - 0 AS Seguro, - i.image, - pr.name AS producer - FROM vn.buy b - JOIN vn.entry e ON b.entryFk = e.id - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk - JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk - JOIN vn.item i ON i.id = b.itemFk - JOIN vn.itemType it ON it.id =i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.packaging pkg ON pkg.id = b.packageFk - LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk - LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk - LEFT JOIN vn.origin o ON o.id = i.originFk - LEFT JOIN vn.supplier s ON s.id = e.supplierFk - LEFT JOIN vn.producer pr on pr.id = i.producerFk - LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway - WHERE - NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid - AND e.id = 158772 - AND i.typeFk IS NOT NULL - AND ic.merchandise IS NOT FALSE; +BEGIN + SELECT + b.quantity / b.packing AS Paquetes, + b.packing AS `Grouping`, + barcode, + 'ASEGURADO' AS asegurado, + ic.name, + ic.order, + s.name AS Consignatario, + e.supplierFk AS Id_Cliente, + e.isOrdered, + e.isConfirmed, + 10 AS Calidad, + LPAD(IFNULL(cpd.id, ip.code), + 5, + '0') AS path, + b.entryFk AS Id_Ticket, + t.landed AS Fecha, + b.itemFk, + b.quantity, + i.name AS Concepte, + i.size, + i.inkFk, + i.category, + o.code AS Origen, + 0 AS Bultos, + wIn.`name` AS Tipo, + 0 AS OK, + 0 AS Reservado, + i.stems, + b.id AS Id_Movimiento, + ip.code, + 'PEDIDO ASEGURADO' AS MSG, + 0 AS Seguro, + i.image, + pr.name AS producer + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk + JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id =i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.packaging pkg ON pkg.id = b.packageFk + LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk + LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN vn.supplier s ON s.id = e.supplierFk + LEFT JOIN vn.producer pr on pr.id = i.producerFk + LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway + WHERE + NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid + AND e.id = 158772 + AND i.typeFk IS NOT NULL + AND ic.merchandise IS NOT FALSE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43012,38 +43012,38 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemLastEntries`(IN `vItem` INT, IN `vDays` DATE) -BEGIN - SELECT - w.id AS warehouseFk, - w.name AS warehouse, - tr.landed, - b.entryFk, - b.isIgnored, - b.price2, - b.price3, - b.stickers, - b.packing, - b.`grouping`, - b.groupingMode, - i.stems, - b.quantity, - b.buyingValue, - b.packageFk , - s.id AS supplierFk, - s.name AS supplier - FROM itemType it - RIGHT JOIN (entry e - LEFT JOIN supplier s ON s.id = e.supplierFk - RIGHT JOIN buy b ON b.entryFk = e.id - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk - LEFT JOIN travel tr ON tr.id = e.travelFk - LEFT JOIN warehouse w ON w.id = tr.warehouseInFk - LEFT JOIN origin o ON o.id = i.originFk - ) ON it.id = i.typeFk - LEFT JOIN edi.ekt ek ON b.ektFk = ek.id - WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND DATE_ADD(CURDATE(), INTERVAl + 10 DAY) - ORDER BY tr.landed DESC , b.id DESC; +BEGIN + SELECT + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.`grouping`, + b.groupingMode, + i.stems, + b.quantity, + b.buyingValue, + b.packageFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND DATE_ADD(CURDATE(), INTERVAl + 10 DAY) + ORDER BY tr.landed DESC , b.id DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47362,77 +47362,77 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake`(IN `vTicketFk` INT, IN `vSectorFk` INT) -BEGIN - - SET @rest:= CAST(0 AS DECIMAL(10,0)); - SET @saleFk := CAST(0 AS DECIMAL(10,0)); - SET @reserved := CAST(0 AS DECIMAL(10,0)); - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN sale s ON s.id = sis.saleFk - SET ish.visible = sis.quantity + ish.visible, - ish.available = sis.quantity + ish.visible - WHERE s.ticketFk = vTicketFk; - - DELETE sis.* - FROM saleItemShelving sis - JOIN sale s ON s.id = sis.saleFk - WHERE s.ticketFk = vTicketFk; - - INSERT INTO saleItemShelving( saleFk, - itemShelvingFk, - quantity, - ubication) - SELECT saleFk, - itemShelvingFk, - CAST(Reserved as DECIMAL(10,0)) as Reserved, - ubication - FROM - (SELECT saleFk, - itemShelvingFk, - ubication, - @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, - @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, - @rest := @rest - @reserved, - @saleFk := saleFk - FROM - ( SELECT s.id as saleFk, - ish.created, - ish.id as itemShelvingFk, - ish.available, - s.quantity, - ish.packing, - CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk - JOIN vn.parking p ON p.sectorFk = sc.id - JOIN vn.shelving sh ON sh.parkingFk = p.id - JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk - WHERE t.id = vTicketFk - AND sc.id = vSectorFk - AND s.quantity MOD ish.packing = 0 - AND s.quantity >= ish.packing - ORDER BY s.id, - sh.priority DESC, - ish.packing DESC, - ish.created - ) sub - ) sub2 - WHERE Reserved > 0; - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN vn.sale s ON s.id = sis.saleFk - SET ish.available = ish.visible - sis.quantity, - ish.visible = ish.visible - sis.quantity - WHERE s.ticketFk = vTicketFk - AND s.isPicked = FALSE; - - CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); - - +BEGIN + + SET @rest:= CAST(0 AS DECIMAL(10,0)); + SET @saleFk := CAST(0 AS DECIMAL(10,0)); + SET @reserved := CAST(0 AS DECIMAL(10,0)); + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN sale s ON s.id = sis.saleFk + SET ish.visible = sis.quantity + ish.visible, + ish.available = sis.quantity + ish.visible + WHERE s.ticketFk = vTicketFk; + + DELETE sis.* + FROM saleItemShelving sis + JOIN sale s ON s.id = sis.saleFk + WHERE s.ticketFk = vTicketFk; + + INSERT INTO saleItemShelving( saleFk, + itemShelvingFk, + quantity, + ubication) + SELECT saleFk, + itemShelvingFk, + CAST(Reserved as DECIMAL(10,0)) as Reserved, + ubication + FROM + (SELECT saleFk, + itemShelvingFk, + ubication, + @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, + @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, + @rest := @rest - @reserved, + @saleFk := saleFk + FROM + ( SELECT s.id as saleFk, + ish.created, + ish.id as itemShelvingFk, + ish.available, + s.quantity, + ish.packing, + CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk + JOIN vn.parking p ON p.sectorFk = sc.id + JOIN vn.shelving sh ON sh.parkingFk = p.id + JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk + WHERE t.id = vTicketFk + AND sc.id = vSectorFk + AND s.quantity MOD ish.packing = 0 + AND s.quantity >= ish.packing + ORDER BY s.id, + sh.priority DESC, + ish.packing DESC, + ish.created + ) sub + ) sub2 + WHERE Reserved > 0; + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN vn.sale s ON s.id = sis.saleFk + SET ish.available = ish.visible - sis.quantity, + ish.visible = ish.visible - sis.quantity + WHERE s.ticketFk = vTicketFk + AND s.isPicked = FALSE; + + CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47925,33 +47925,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `scanTreeCreate`() -BEGIN - CALL nestTree( - 'vn2008', - 'scan', - 'vn2008', - 'scanTree' - ); - - UPDATE vn2008.scanTree st - JOIN ( - SELECT sl.scan_id, - MAX(sl.odbc_date) lastScanned, - COUNT(DISTINCT t.routeFk) routeCount, - MIN(t.routeFk) mod 1000 as minRoute, - MAX(t.routeFk) mod 1000 as maxRoute, - COUNT(sl.scan_line_id) as scanned - FROM vn2008.scan_line sl - JOIN expedition e ON e.id = sl.`code` - JOIN ticket t ON t.id = e.ticketFk - WHERE t.routeFk - GROUP BY sl.scan_id - ) rs ON rs.scan_id = st.id - SET st.lastScanned = rs.lastScanned, - st.routeCount = rs.routeCount, - st.minRoute = rs.minRoute, - st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), - st.scanned = rs.scanned; +BEGIN + CALL nestTree( + 'vn2008', + 'scan', + 'vn2008', + 'scanTree' + ); + + UPDATE vn2008.scanTree st + JOIN ( + SELECT sl.scan_id, + MAX(sl.odbc_date) lastScanned, + COUNT(DISTINCT t.routeFk) routeCount, + MIN(t.routeFk) mod 1000 as minRoute, + MAX(t.routeFk) mod 1000 as maxRoute, + COUNT(sl.scan_line_id) as scanned + FROM vn2008.scan_line sl + JOIN expedition e ON e.id = sl.`code` + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk + GROUP BY sl.scan_id + ) rs ON rs.scan_id = st.id + SET st.lastScanned = rs.lastScanned, + st.routeCount = rs.routeCount, + st.minRoute = rs.minRoute, + st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), + st.scanned = rs.scanned; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; From dbb225743089fc9ecd31cc4cf4aa8b169062bda1 Mon Sep 17 00:00:00 2001 From: jgallego Date: Mon, 20 Apr 2020 13:49:33 +0200 Subject: [PATCH 19/25] test de zone_getLanded y zone_getFromGeo --- .../10180-holyWeek/02-catalog_calculate.sql | 147 ++++++++++ .../02-catalog_componentCalculate.sql | 262 ++++++++++++++++++ .../02-catalog_componentPrepare.sql | 33 +++ .../02-catalog_componentPurge.sql | 16 ++ .../02-order_confirmWithUser.sql | 250 +++++++++++++++++ .../02-sale_calculateComponent.sql | 77 +++++ .../10180-holyWeek/02-ticketCalculateClon.sql | 91 ++++++ .../10180-holyWeek/02-ticketCalculateSale.sql | 67 +++++ .../02-ticketCalculateSaleForcePrice.sql | 61 ++++ .../02-ticketCalculateSaleForcePrice2.sql | 61 ++++ .../02-ticket_componentPreview.sql | 113 ++++++++ .../02-ticket_recalcComponents.sql | 78 ++++++ .../02-ticket_recalcComponentsForcePrice.sql | 78 ++++++ db/tests/vn/zone_getFromGeo.spec.js | 28 ++ db/tests/vn/zone_getLanded.spec.js | 66 +++++ e2e/paths/05-ticket/12_descriptor.spec.js | 3 +- modules/client/front/summary/index.html | 2 +- .../back/methods/ticket-request/confirm.js | 3 +- modules/ticket/back/methods/ticket/addSale.js | 2 +- modules/ticket/front/locale/es.yml | 2 +- modules/zone/front/create/index.html | 2 +- modules/zone/front/create/locale/es.yml | 2 +- modules/zone/front/descriptor/index.html | 2 +- modules/zone/front/index/index.html | 2 +- modules/zone/front/summary/index.html | 2 +- package-lock.json | 38 +-- 26 files changed, 1458 insertions(+), 30 deletions(-) create mode 100644 db/changes/10180-holyWeek/02-catalog_calculate.sql create mode 100644 db/changes/10180-holyWeek/02-catalog_componentCalculate.sql create mode 100644 db/changes/10180-holyWeek/02-catalog_componentPrepare.sql create mode 100644 db/changes/10180-holyWeek/02-catalog_componentPurge.sql create mode 100644 db/changes/10180-holyWeek/02-order_confirmWithUser.sql create mode 100644 db/changes/10180-holyWeek/02-sale_calculateComponent.sql create mode 100644 db/changes/10180-holyWeek/02-ticketCalculateClon.sql create mode 100644 db/changes/10180-holyWeek/02-ticketCalculateSale.sql create mode 100644 db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice.sql create mode 100644 db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice2.sql create mode 100644 db/changes/10180-holyWeek/02-ticket_componentPreview.sql create mode 100644 db/changes/10180-holyWeek/02-ticket_recalcComponents.sql create mode 100644 db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice.sql create mode 100644 db/tests/vn/zone_getFromGeo.spec.js create mode 100644 db/tests/vn/zone_getLanded.spec.js diff --git a/db/changes/10180-holyWeek/02-catalog_calculate.sql b/db/changes/10180-holyWeek/02-catalog_calculate.sql new file mode 100644 index 000000000..b18d85710 --- /dev/null +++ b/db/changes/10180-holyWeek/02-catalog_calculate.sql @@ -0,0 +1,147 @@ +USE `vn`; +DROP procedure IF EXISTS `catalog_calculate`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +/** + * Calcula los articulos disponibles y sus precios + * + * @table tmp.item(itemFk) Listado de artículos a calcular + * @param vLanded Fecha de recepcion de mercancia + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.ticketCalculateItem(itemFk, available, producer, + * item, size, stems, category, inkFk, image, origin, price) + * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) + * @return tmp.ticketComponent + * @return tmp.ticketComponentPrice + * @return tmp.zoneGetShipped + */ + + DECLARE vAvailableCalc INT; + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vZoneFk INT; + DECLARE vDone BOOL; + DECLARE cTravelTree CURSOR FOR + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + -- Establece los almacenes y las fechas que van a entrar al disponible + + CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `available` double DEFAULT NULL, + `buyFk` int(11) DEFAULT NULL, + `fix` tinyint(3) unsigned DEFAULT '0', + `zoneFk` int(11) NOT NULL, + KEY `itemFk` (`itemFk`), + KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH + ) ENGINE=MEMORY DEFAULT CHARSET=utf8; + + CALL catalog_componentPrepare(); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; + CREATE TEMPORARY TABLE tmp.ticketCalculateItem( + itemFk INT(11) NOT NULL, + available INT(11), + producer VARCHAR(50), + item VARCHAR(50), + size INT(10) UNSIGNED, + stems INT(11), + category VARCHAR(3), + inkFk VARCHAR(3), + image VARCHAR(50), + origin VARCHAR(3), + price DECIMAL(10,2), + priceKg DECIMAL(10,2), + KEY `itemFk` (`itemFk`) + ) ENGINE = MEMORY DEFAULT CHARSET=utf8; + + OPEN cTravelTree; + + l: LOOP + SET vDone = FALSE; + FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); + CALL buyUltimate (vWarehouseFk, vShipped); + + INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk) + SELECT vWarehouseFk, + i.item_id, + IFNULL(i.available, 0), + bu.buyFk, + vZoneFk + FROM `cache`.available i + JOIN tmp.item br ON br.itemFk = i.item_id + LEFT JOIN item it ON it.id = i.item_id + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id + WHERE i.calc_id = vAvailableCalc + AND i.available > 0; + + DROP TEMPORARY TABLE tmp.buyUltimate; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + INSERT INTO tmp.ticketCalculateItem ( + itemFk, + available, + producer, + item, + size, + stems, + category, + inkFk, + image, + origin, + price, + priceKg) + SELECT + tl.itemFk, + SUM(tl.available) available, + p.name producer, + i.name item, + i.size size, + i.stems, + i.category, + i.inkFk, + i.image, + o.code origin, + bl.price, + bl.priceKg + FROM tmp.ticketLot tl + JOIN item i ON tl.itemFk = i.id + LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible + JOIN origin o ON o.id = i.originFk + JOIN ( + SELECT MIN(price) price, itemFk, priceKg + FROM tmp.ticketComponentPrice + GROUP BY itemFk + ) bl ON bl.itemFk = tl.itemFk + WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk + GROUP BY tl.itemFk; + -- on duplicatekey update + + END LOOP; + + CLOSE cTravelTree; + +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-catalog_componentCalculate.sql b/db/changes/10180-holyWeek/02-catalog_componentCalculate.sql new file mode 100644 index 000000000..04ec1330a --- /dev/null +++ b/db/changes/10180-holyWeek/02-catalog_componentCalculate.sql @@ -0,0 +1,262 @@ +USE `vn`; +DROP procedure IF EXISTS `catalog_componentCalculate`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`( + vZoneFk INT, + vAddressFk INT, + vShipped DATE, + vWarehouseFk INT) +proc: BEGIN +/** + * Calcula los componentes de los articulos de tmp.ticketLot + * + * @param vZoneFk para calcular el transporte + * @param vAddressFk Consignatario + * @param vShipped dia de salida del pedido + * @param tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) + * + * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, + * packing, grouping, groupingMode, buyFk, typeFk) + * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) + */ + DECLARE vClientFk INT; + DECLARE vGeneralInflationCoefficient INT DEFAULT 1; + DECLARE vMinimumDensityWeight INT DEFAULT 167; + DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; + DECLARE vSpecialPriceComponent INT DEFAULT 10; + DECLARE vDeliveryComponent INT DEFAULT 15; + DECLARE vRecoveryComponent INT DEFAULT 17; + DECLARE vSellByPacketComponent INT DEFAULT 22; + DECLARE vBuyValueComponent INT DEFAULT 28; + DECLARE vMarginComponent INT DEFAULT 29; + DECLARE vDiscountLastItemComponent INT DEFAULT 32; + DECLARE vExtraBaggedComponent INT DEFAULT 38; + DECLARE vManaAutoComponent INT DEFAULT 39; + + SELECT volume INTO vBoxVolume + FROM vn.packaging + WHERE id = '94'; + + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; + + SET @rate2 := 0; + SET @rate3 := 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT + tl.itemFk, tl.warehouseFk, tl.available, + IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, + IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, + IFNULL(pf.rate3, 0) AS minPrice, + IFNULL(pf.packing, b.packing) packing, + IFNULL(pf.`grouping`, b.`grouping`) `grouping`, + ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, + tl.buyFk, + i.typeFk, + IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping + FROM tmp.ticketLot tl + JOIN buy b ON b.id = tl.buyFk + JOIN item i ON i.id = tl.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk + LEFT JOIN ( + SELECT * FROM ( + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk + FROM priceFixed pf + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) + WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC + ) tpf + GROUP BY tpf.itemFk, tpf.warehouseFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0 + AND tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk; + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vBuyValueComponent, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vMarginComponent, + tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; + CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY + SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk + FROM tmp.ticketComponent tc + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk + GROUP BY tc.itemFk, warehouseFk; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.priceIncreasing, 0.25), 3) + FROM tmp.ticketComponentBase tcb + JOIN claimRatio cr ON cr.clientFk = vClientFk + WHERE cr.priceIncreasing > 0.009; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto + FROM tmp.ticketComponentBase tcb + JOIN `client` c on c.id = vClientFk + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + WHERE wm.isPricesModifierActivated + HAVING manaAuto <> 0; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, + tcb.itemFk, + c.id, + GREATEST(IFNULL(ROUND(tcb.base * c.tax, 4), 0), tcc.minPrice - tcc.rate3) + FROM tmp.ticketComponentBase tcb + JOIN component c + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE c.id = vDiscountLastItemComponent AND c.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE sp.value IS NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.zone; + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.zone (INDEX (id)) + ENGINE = MEMORY + SELECT vZoneFk id; + + CALL zone_getOptionsForShipment(vShipped, TRUE); + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + vDeliveryComponent, + vGeneralInflationCoefficient + * ROUND(( + i.compression + * ic.cm3 + * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) + * IFNULL((zo.price - zo.bonus) + * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 + ) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN tmp.zoneOption zo ON zo.zoneFk = vZoneFk + JOIN zone z ON z.id = vZoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk + AND ic.itemFk = tcc.itemFk + HAVING cost <> 0; + + DROP TEMPORARY TABLE tmp.zoneOption; + + IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost + FROM tmp.ticketComponentCalculate tcc + JOIN vn.addressForPackaging ap + WHERE ap.addressFk = vAddressFk; + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; + CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY + SELECT * FROM tmp.ticketComponent; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + vSpecialPriceComponent, + sp.value - SUM(tcc.cost) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN component c ON c.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + WHERE c.classRate IS NULL + GROUP BY tcc.itemFk, tcc.warehouseFk + HAVING ABS(sumCost) > 0.001; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; + CREATE TEMPORARY TABLE tmp.ticketComponentSum + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, c.classRate + FROM tmp.ticketComponent tc + JOIN component c ON c.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, c.classRate; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; + CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY + SELECT tcc.warehouseFk, + tcc.itemFk, + 1 rate, + IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 1) = 1 + AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 2 rate, + tcc.packing `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 + AND tcc.packing > 0 AND tcc.available >= tcc.packing) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 3) = 3 + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT * FROM ( + SELECT * FROM tmp.ticketComponentRate ORDER BY price + ) t + GROUP BY itemFk, warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketComponentCalculate, + tmp.ticketComponentSum, + tmp.ticketComponentBase, + tmp.ticketComponentRate, + tmp.ticketComponentCopy; + +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-catalog_componentPrepare.sql b/db/changes/10180-holyWeek/02-catalog_componentPrepare.sql new file mode 100644 index 000000000..98b93a97e --- /dev/null +++ b/db/changes/10180-holyWeek/02-catalog_componentPrepare.sql @@ -0,0 +1,33 @@ +USE `vn`; +DROP procedure IF EXISTS `catalog_componentPrepare`; + +DELIMITER $$ +USE `vn`$$ +CREATE PROCEDURE `catalog_componentPrepare` () +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + CREATE TEMPORARY TABLE tmp.ticketComponent ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `componentFk` INT UNSIGNED NOT NULL, + `cost` DECIMAL(10,4) NOT NULL, + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC) + )ENGINE=MEMORY DEFAULT CHARSET=utf8; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `rate` INT NOT NULL, + `grouping` INT UNSIGNED NOT NULL, + `price` DECIMAL(10,4) NOT NULL, + `priceKg` DECIMAL(10,4), + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE `fkItemWarehouseRate` (`itemFk` ASC, `warehouseFk` ASC, `rate` ASC) + )ENGINE=MEMORY DEFAULT CHARSET=utf8; +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-catalog_componentPurge.sql b/db/changes/10180-holyWeek/02-catalog_componentPurge.sql new file mode 100644 index 000000000..2b744b5f0 --- /dev/null +++ b/db/changes/10180-holyWeek/02-catalog_componentPurge.sql @@ -0,0 +1,16 @@ + +USE `vn`; +DROP procedure IF EXISTS `vn`.`catalog_componentPurge`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentPurge`() +BEGIN + DROP TEMPORARY TABLE + tmp.ticketComponentPrice, + tmp.ticketComponent, + tmp.ticketLot; +END$$ + +DELIMITER ; +; diff --git a/db/changes/10180-holyWeek/02-order_confirmWithUser.sql b/db/changes/10180-holyWeek/02-order_confirmWithUser.sql new file mode 100644 index 000000000..c9acdc038 --- /dev/null +++ b/db/changes/10180-holyWeek/02-order_confirmWithUser.sql @@ -0,0 +1,250 @@ +USE `hedera`; +DROP procedure IF EXISTS `order_confirmWithUser`; + +DELIMITER $$ +USE `hedera`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `order_confirmWithUser`(IN `vOrder` INT, IN `vUserId` INT) +BEGIN +/** + * Confirms an order, creating each of its tickets on the corresponding + * date, store and user. + * + * @param vOrder The order identifier + * @param vUser The user identifier + */ + DECLARE vOk BOOL; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vWarehouse INT; + DECLARE vShipment DATETIME; + DECLARE vTicket INT; + DECLARE vNotes VARCHAR(255); + DECLARE vItem INT; + DECLARE vConcept VARCHAR(30); + DECLARE vAmount INT; + DECLARE vPrice DECIMAL(10,2); + DECLARE vSale INT; + DECLARE vRate INT; + DECLARE vRowId INT; + DECLARE vDelivery DATE; + DECLARE vAddress INT; + DECLARE vIsConfirmed BOOL; + DECLARE vClientId INT; + DECLARE vCompanyId INT; + DECLARE vAgencyModeId INT; + DECLARE TICKET_FREE INT DEFAULT 2; + + DECLARE cDates CURSOR FOR + SELECT zgs.shipped, r.warehouse_id + FROM `order` o + JOIN order_row r ON r.order_id = o.id + LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id + WHERE o.id = vOrder AND r.amount != 0 + GROUP BY r.warehouse_id; + + DECLARE cRows CURSOR FOR + SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate + FROM order_row r + JOIN vn.item i ON i.id = r.item_id + WHERE r.amount != 0 + AND r.warehouse_id = vWarehouse + AND r.order_id = vOrder + ORDER BY r.rate DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + -- Carga los datos del pedido + + SELECT o.date_send, o.address_id, o.note, + o.confirmed, a.clientFk, o.company_id, o.agency_id + INTO vDelivery, vAddress, vNotes, + vIsConfirmed, vClientId, vCompanyId, vAgencyModeId + FROM hedera.`order` o + JOIN vn.address a ON a.id = o.address_id + WHERE o.id = vOrder; + + -- Comprueba que el pedido no está confirmado + + IF vIsConfirmed THEN + CALL util.throw ('ORDER_ALREADY_CONFIRMED'); + END IF; + + -- Comprueba que el pedido no está vacío + + SELECT COUNT(*) > 0 INTO vOk + FROM order_row WHERE order_id = vOrder AND amount > 0; + + IF NOT vOk THEN + CALL util.throw ('ORDER_EMPTY'); + END IF; + + -- Carga las fechas de salida de cada almacén + + CALL vn.zone_getShipped (vDelivery, vAddress, vAgencyModeId, FALSE); + + -- Trabajador que realiza la acción + + IF vUserId IS NULL THEN + SELECT employeeFk INTO vUserId FROM orderConfig; + END IF; + + -- Crea los tickets del pedido + + START TRANSACTION; + + OPEN cDates; + + lDates: + LOOP + SET vTicket = NULL; + SET vDone = FALSE; + FETCH cDates INTO vShipment, vWarehouse; + + IF vDone THEN + LEAVE lDates; + END IF; + + -- Busca un ticket existente que coincida con los parametros + + SELECT t.id INTO vTicket + FROM vn.ticket t + LEFT JOIN vn.ticketState tls on tls.ticket = t.id + JOIN `order` o + ON o.address_id = t.addressFk + AND vWarehouse = t.warehouseFk + AND o.agency_id = t.agencyModeFk + AND o.date_send = t.landed + AND vShipment = DATE(t.shipped) + WHERE o.id = vOrder + AND t.invoiceOutFk IS NULL + AND IFNULL(tls.alertLevel,0) = 0 + AND t.clientFk <> 1118 + LIMIT 1; + + -- Crea el ticket en el caso de no existir uno adecuado + + IF vTicket IS NULL + THEN + CALL vn.ticketCreateWithUser( + vClientId, + IFNULL(vShipment, CURDATE()), + vWarehouse, + vCompanyId, + vAddress, + vAgencyModeId, + NULL, + vDelivery, + vUserId, + vTicket + ); + ELSE + INSERT INTO vncontrol.inter + SET Id_Ticket = vTicket, + Id_Trabajador = vUserId, + state_id = TICKET_FREE; + END IF; + + INSERT IGNORE INTO vn.orderTicket + SET orderFk = vOrder, + ticketFk = vTicket; + + -- Añade las notas + + IF vNotes IS NOT NULL AND vNotes != '' + THEN + INSERT INTO vn.ticketObservation SET + ticketFk = vTicket, + observationTypeFk = 4 /* salesperson */ , + `description` = vNotes + ON DUPLICATE KEY UPDATE + `description` = CONCAT(VALUES(`description`),'. ', `description`); + END IF; + + -- Añade los movimientos y sus componentes + + OPEN cRows; + + lRows: + LOOP + SET vDone = FALSE; + FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate; + + IF vDone THEN + LEAVE lRows; + END IF; + SET vSale = NULL; + SELECT s.id INTO vSale + FROM vn.sale s + WHERE ticketFk = vTicket + AND price = vPrice + AND itemFk = vItem + LIMIT 1; + IF vSale THEN + UPDATE vn.sale + SET quantity = quantity + vAmount + WHERE id = vSale; + ELSE + INSERT INTO vn.sale + SET + itemFk = vItem, + ticketFk = vTicket, + concept = vConcept, + quantity = vAmount, + price = vPrice, + priceFixed = 0, + isPriceFixed = TRUE; + + SET vSale = LAST_INSERT_ID(); + + INSERT INTO vn.saleComponent + (saleFk, componentFk, `value`) + SELECT vSale, cm.component_id, cm.price + FROM order_component cm + JOIN vn.component c ON c.id = cm.component_id + WHERE cm.order_row_id = vRowId + GROUP BY vSale, cm.component_id; + END IF; + UPDATE order_row SET Id_Movimiento = vSale + WHERE id = vRowId; + + END LOOP; + + CLOSE cRows; + + -- Fija el coste + + DROP TEMPORARY TABLE IF EXISTS tComponents; + CREATE TEMPORARY TABLE tComponents + (INDEX (saleFk)) + ENGINE = MEMORY + SELECT SUM(sc.`value`) valueSum, sc.saleFk + FROM vn.saleComponent sc + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk AND ct.isBase + JOIN vn.sale s ON s.id = sc.saleFk + WHERE s.ticketFk = vTicket + GROUP BY sc.saleFk; + + UPDATE vn.sale s + JOIN tComponents mc ON mc.saleFk = s.id + SET s.priceFixed = valueSum; + + DROP TEMPORARY TABLE tComponents; + END LOOP; + + CLOSE cDates; + + DELETE FROM basketOrder WHERE orderFk = vOrder; + UPDATE `order` SET confirmed = TRUE, confirm_date = NOW() + WHERE id = vOrder; + + COMMIT; +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10180-holyWeek/02-sale_calculateComponent.sql b/db/changes/10180-holyWeek/02-sale_calculateComponent.sql new file mode 100644 index 000000000..5158bd26c --- /dev/null +++ b/db/changes/10180-holyWeek/02-sale_calculateComponent.sql @@ -0,0 +1,77 @@ +USE `vn`; +DROP procedure IF EXISTS `sale_calculateComponent`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `sale_calculateComponent`(vSale INT, vOption INT) +proc: BEGIN +/** + * Actualiza los componentes + * + * @param vSale Delivery date + * @param vOption indica en que componente pone el descuadre, NULL en casos habituales + * @return tmp.ticketLot(warehouseFk, available, itemFk, buyFk) + * @return tmp.sale(saleFk, warehouseFk) + */ + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vTicket BIGINT; + DECLARE vItem BIGINT; + DECLARE vLanded DATE; + DECLARE vTicketFree BOOLEAN DEFAULT TRUE; + DECLARE vZoneFk INTEGER; + + SELECT NOT (t.refFk IS NOT NULL OR ts.alertLevel > 0) OR s.price = 0, s.ticketFk, s.itemFk , t.zoneFk + INTO vTicketFree, vTicket, vItem, vZoneFk + FROM vn.ticket t + JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id + WHERE s.id = vSale + LIMIT 1; + + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicket; + + IF IFNULL(vZoneFk,0) = 0 THEN + CALL util.throw('ticket dont have zone'); + END IF; + + CALL buyUltimate (vWarehouseFk, vShipped); + + DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk, vZoneFk zoneFk + FROM tmp.buyUltimate + WHERE itemFk = vItem; + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT vSale saleFk,vWarehouseFk warehouseFk; + + IF vOption IS NULL THEN + SET vOption = IF(vTicketFree, 1, 6); + END IF; + + CALL ticketComponentUpdateSale(vOption); + + INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) + VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.sale; +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-ticketCalculateClon.sql b/db/changes/10180-holyWeek/02-ticketCalculateClon.sql new file mode 100644 index 000000000..bd44f592f --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticketCalculateClon.sql @@ -0,0 +1,91 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketCalculateClon`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT) +BEGIN + /* + * @vTicketNew id del nuevo ticket clonado + * @vTicketOld id ticket original, a partir del qual se clonara el nuevo + * Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo + */ + DECLARE vShipped DATE; + DECLARE vClient INT; + DECLARE vWarehouse SMALLINT; + DECLARE vAgencyMode INT; + DECLARE vAddress INT; + DECLARE vLanded DATE; + DECLARE vAgency INT; + DECLARE vZoneFk INT; + + REPLACE INTO orderTicket(orderFk,ticketFk) + SELECT orderFk, vTicketNew + FROM orderTicket + WHERE ticketFk = vTicketOld; + + SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk + INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk + FROM vn.agencyMode a + JOIN vn.ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicketNew; + + IF vLanded IS NULL THEN + CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse); + UPDATE ticket t + JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk + SET t.landed = zgl.landed, + t.zone = zgl.zoneFk + WHERE t.id = vTicketNew; + + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + END IF; + + -- rellena la tabla tmp.buyUltimate con la ultima compra + CALL buyUltimate(vWarehouse, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk, vZoneFk zoneFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode, vWarehouse); + + -- Bionizamos lineas con Preu = 0 + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT s.id saleFk, vWarehouse warehouseFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew AND s.price = 0; + + CALL ticketComponentUpdateSale(1); + + -- Bionizamos lineas con Preu > 0 + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT s.id saleFk, vWarehouse warehouseFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew + AND s.price > 0; + + CALL ticketComponentUpdateSale(6); + + -- Log + CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); + + -- Limpieza + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-ticketCalculateSale.sql b/db/changes/10180-holyWeek/02-ticketCalculateSale.sql new file mode 100644 index 000000000..aea966ed1 --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticketCalculateSale.sql @@ -0,0 +1,67 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketCalculateSale`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSale`(IN vSale BIGINT) +proc: BEGIN +-- OBSOLETO USAR: sale_calculateComponent(vSale, NULL) + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vTicket BIGINT; + DECLARE vItem BIGINT; + DECLARE vLanded DATE; + DECLARE vTicketFree BOOLEAN DEFAULT TRUE; + DECLARE vZoneFk INTEGER; + + SELECT NOT (t.refFk IS NOT NULL OR ts.alertLevel > 0) OR s.price = 0, s.ticketFk, s.itemFk , t.zoneFk + INTO vTicketFree, vTicket, vItem, vZoneFk + FROM vn.ticket t + JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id + WHERE s.id = vSale + LIMIT 1; + + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicket; + + IF IFNULL(vZoneFk,0) = 0 THEN + CALL util.throw('ticket dont have zone'); + END IF; + + CALL buyUltimate (vWarehouseFk, vShipped); + + DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk, vZoneFk zoneFk + FROM tmp.buyUltimate + WHERE itemFk = vItem; + + CALL vn.catalog_componentCalculate; + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT vSale saleFk,vWarehouseFk warehouseFk; + + CALL ticketComponentUpdateSale(IF(vTicketFree,1,6)); + + INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) + VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CALL catalog_componentPurge(); + +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice.sql b/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice.sql new file mode 100644 index 000000000..99ecf739e --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice.sql @@ -0,0 +1,61 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketCalculateSaleForcePrice`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice`(IN vSale BIGINT) +proc: BEGIN + + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAddressFk INT; + DECLARE vTicket BIGINT; + DECLARE vItem BIGINT; + DECLARE vZoneFk INT; + + SELECT ticketFk, itemFk + INTO vTicket, vItem + FROM sale + WHERE id = vSale; + + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicket; + + IF vZoneFk IS NULL THEN + CALL util.throw('ticket without zone'); + END IF; + + CALL buyUltimate (vWarehouseFk, vShipped); + + DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk, vZoneFk zoneFk + FROM tmp.buyUltimate + WHERE itemFk = vItem; + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT vSale saleFk,vWarehouseFk warehouseFk; + + CALL ticketComponentUpdateSale(1); + + INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) + VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.sale; + +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice2.sql b/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice2.sql new file mode 100644 index 000000000..89f4320f2 --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice2.sql @@ -0,0 +1,61 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketCalculateSaleForcePrice2`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice2`(IN vSale BIGINT) +proc: BEGIN + + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAddressFk INT; + DECLARE vTicket BIGINT; + DECLARE vItem BIGINT; + DECLARE vZoneFk INT; + + SELECT ticketFk, itemFk + INTO vTicket, vItem + FROM sale + WHERE id = vSale; + + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicket; + + IF vZoneFk IS NULL THEN + CALL util.throw('ticket without zone'); + END IF; + + CALL buyUltimate (vWarehouseFk, vShipped); + + DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk, vZoneFk zoneFk + FROM tmp.buyUltimate + WHERE itemFk = vItem; + + CALL vn.catalog_componentCalculate; + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT vSale saleFk,vWarehouseFk warehouseFk; + + CALL ticketComponentUpdateSale(1); + + INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) + VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.sale; + CALL catalog_componentPurge(); + +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-ticket_componentPreview.sql b/db/changes/10180-holyWeek/02-ticket_componentPreview.sql new file mode 100644 index 000000000..bec56025d --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticket_componentPreview.sql @@ -0,0 +1,113 @@ +USE `vn`; +DROP procedure IF EXISTS `ticket_componentPreview`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentPreview`( + vTicketFk INT, + vLanded DATE, + vAddressFk INT, + vZoneFk INT, + vWarehouseFk SMALLINT) +BEGIN +/** + * Calcula los componentes de los articulos de un ticket + * + * @param vTicketFk id del ticket + * @param vLanded nueva fecha de entrega + * @param vAddressFk nuevo consignatario + * @param vZoneFk nueva zona + * @param vWarehouseFk nuevo warehouse + * + * @return tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + */ + DECLARE vShipped DATE; + DECLARE vBuyOrderItem INT DEFAULT 100; + + DECLARE vHasDataChanged BOOL DEFAULT FALSE; + DECLARE vHasAddressChanged BOOL; + DECLARE vHasZoneChanged BOOL DEFAULT FALSE; + DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE; + + DECLARE vAddressTypeRateFk INT DEFAULT NULL; + DECLARE vAgencyModeTypeRateFk INT DEFAULT NULL; + + DECLARE vHasChangeAll BOOL DEFAULT FALSE; + + SELECT DATE(landed) <> vLanded, + addressFk <> vAddressFk, + zoneFk <> vZoneFk, + warehouseFk <> vWarehouseFk + INTO + vHasDataChanged, + vHasAddressChanged, + vHasZoneChanged, + vHasWarehouseChanged + FROM vn.ticket t + WHERE t.id = vTicketFk; + + IF vHasDataChanged OR vHasWarehouseChanged THEN + SET vHasChangeAll = TRUE; + END IF; + + IF vHasAddressChanged THEN + SET vAddressTypeRateFk = 5; + END IF; + + IF vHasZoneChanged THEN + SET vAgencyModeTypeRateFk = 6; + END IF; + + SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped + FROM zone + WHERE id = vZoneFk; + + CALL buyUltimate(vWarehouseFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( + SELECT + vWarehouseFk AS warehouseFk, + NULL AS available, + s.itemFk, + bu.buyFk, + vZoneFk zoneFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + AND s.itemFk != vBuyOrderItem + GROUP BY bu.warehouseFk, bu.itemFk); + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + REPLACE INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT t.warehouseFk, s.itemFk, sc.componentFk, sc.value + FROM saleComponent sc + JOIN sale s ON s.id = sc.saleFk + JOIN ticket t ON t.id = s.ticketFk + JOIN `component` c ON c.id = sc.componentFk + WHERE s.ticketFk = vTicketFk + AND (c.isRenewable = FALSE + OR + (NOT vHasChangeAll + AND (NOT (c.typeFk <=> vAddressTypeRateFk + OR c.typeFk <=> vAgencyModeTypeRateFk)))); + + SET @shipped = vShipped; + + DROP TEMPORARY TABLE + tmp.buyUltimate, + tmp.ticketLot; + + IF vShipped IS NULL THEN + CALL util.throw('NO_ZONE_AVAILABLE'); + END IF; + + IF vShipped < CURDATE() THEN + CALL util.throw('ERROR_PAST_SHIPMENT'); + END IF; +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-ticket_recalcComponents.sql b/db/changes/10180-holyWeek/02-ticket_recalcComponents.sql new file mode 100644 index 000000000..eb124ffdb --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticket_recalcComponents.sql @@ -0,0 +1,78 @@ +USE `vn`; +DROP procedure IF EXISTS `ticket_recalcComponents`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT ) +proc: BEGIN + +/** + * Este procedimiento trata de "rebionizar" un ticket, + * eliminando los componentes existentes e insertandolos de nuevo + * + * @param vTicketFk Id del ticket + * @return tmp.buyUltimate + */ + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vLanded DATE; + DECLARE vIsTicketEditable BOOLEAN; + DECLARE vZoneFk INTEGER; + + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + + SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM ticket + WHERE id = vTicketFk; + + CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); + + CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, + s.itemFk, bu.buyFk, vZoneFk zoneFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY s.itemFk; + + CALL catalog_componentPrepare(); + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + + IF vLanded IS NULL THEN + + CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + UPDATE vn2008.Tickets t + SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) + WHERE Id_Ticket = vTicketFk; + + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + END IF; + + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.ticketComponentPrice; + DROP TEMPORARY TABLE tmp.ticketComponent; + DROP TEMPORARY TABLE tmp.sale; +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice.sql b/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice.sql new file mode 100644 index 000000000..944490d20 --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice.sql @@ -0,0 +1,78 @@ +USE `vn`; +DROP procedure IF EXISTS `ticket_recalcComponentsForcePrice`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN ) +proc: BEGIN + +/** + * Este procedimiento trata de "rebionizar" un ticket, + * eliminando los componentes existentes e insertandolos de nuevo + * + * @param vTicketFk Id del ticket + * @return tmp.buyUltimate + */ + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vLanded DATE; + DECLARE vZoneFk INTEGER; + + IF vIsTicketEditable IS NULL THEN + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + END IF; + SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM ticket + WHERE id = vTicketFk; + + CALL zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, TRUE); + + CALL buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, + s.itemFk, bu.buyFk, vZoneFk zoneFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY s.itemFk; + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + CALL ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + + IF vLanded IS NULL THEN + + CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + UPDATE vn2008.Tickets t + SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) + WHERE Id_Ticket = vTicketFk; + + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + END IF; + + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.ticketComponentPrice; + DROP TEMPORARY TABLE tmp.ticketComponent; + DROP TEMPORARY TABLE tmp.sale; +END$$ + +DELIMITER ; + diff --git a/db/tests/vn/zone_getFromGeo.spec.js b/db/tests/vn/zone_getFromGeo.spec.js new file mode 100644 index 000000000..0dccf92cc --- /dev/null +++ b/db/tests/vn/zone_getFromGeo.spec.js @@ -0,0 +1,28 @@ +const app = require('vn-loopback/server/server'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +describe('zone zone_getFromGeo()', () => { + it(`should check that there are some results in table zone`, async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + let geoFk = 17; + + stmt = new ParameterizedSQL('CALL zone_getFromGeo(?)', [ + geoFk, + ]); + stmts.push(stmt); + + let tableIndex = stmts.push('SELECT count(*) countZone FROM tmp.zone WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8)') - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + let [zoneTable] = result[tableIndex]; + + expect(zoneTable.countZone).toBe(8); + }); +}); diff --git a/db/tests/vn/zone_getLanded.spec.js b/db/tests/vn/zone_getLanded.spec.js new file mode 100644 index 000000000..92c3f435b --- /dev/null +++ b/db/tests/vn/zone_getLanded.spec.js @@ -0,0 +1,66 @@ +const app = require('vn-loopback/server/server'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +describe('zone zone_getLanded()', () => { + it(`should return data for a shipped in the past`, async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + addressFk: 121, + agencyModeFk: 7, + warehouseFk: 1}; + + stmt = new ParameterizedSQL('CALL zone_getLanded(DATE_ADD(CURDATE(), INTERVAL -1 DAY), ?, ?, ?)', [ + params.addressFk, + params.agencyModeFk, + params.warehouseFk + + ]); + stmts.push(stmt); + + let tableIndex = stmts.push('SELECT count(*) countZone FROM tmp.zoneGetLanded') - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + let [zoneTable] = result[tableIndex]; + + expect(zoneTable.countZone).toBe(1); + }); + + it(`should return data for a shipped tomorrow`, async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + addressFk: 121, + agencyModeFk: 7, + warehouseFk: 1}; + + stmt = new ParameterizedSQL('CALL zone_getLanded(DATE_ADD(CURDATE(), INTERVAL +2 DAY), ?, ?, ?)', [ + params.addressFk, + params.agencyModeFk, + params.warehouseFk + + ]); + stmts.push(stmt); + + let tableIndex = stmts.push('SELECT count(*) countZone FROM tmp.zoneGetLanded') - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + let [zoneTable] = result[tableIndex]; + + expect(zoneTable.countZone).toBe(1); + }); +}); diff --git a/e2e/paths/05-ticket/12_descriptor.spec.js b/e2e/paths/05-ticket/12_descriptor.spec.js index 87990bcc5..faeae0c3f 100644 --- a/e2e/paths/05-ticket/12_descriptor.spec.js +++ b/e2e/paths/05-ticket/12_descriptor.spec.js @@ -87,7 +87,8 @@ describe('Ticket descriptor path', () => { expect(message.type).toBe('success'); }); - it(`should check the state of the stowaway ticket is embarked`, async() => { + xit(`should check the state of the stowaway ticket is embarked`, async() => { + await page.wait(500); const state = await page.waitToGetProperty(selectors.ticketDescriptor.stateLabelValue, 'innerText'); expect(state).toEqual('State Embarcando'); diff --git a/modules/client/front/summary/index.html b/modules/client/front/summary/index.html index eccf45873..abd89a6d7 100644 --- a/modules/client/front/summary/index.html +++ b/modules/client/front/summary/index.html @@ -93,7 +93,7 @@ -

Pay method

+

Billing data

diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js index 938efa7e5..fe08794f1 100644 --- a/modules/ticket/back/methods/ticket-request/confirm.js +++ b/modules/ticket/back/methods/ticket-request/confirm.js @@ -57,7 +57,6 @@ module.exports = Self => { if (stock.available < 0) throw new UserError(`This item is not available`); - if (request.saleFk) { sale = await models.Sale.findById(request.saleFk, null, options); await sale.updateAttributes({ @@ -79,7 +78,7 @@ module.exports = Self => { }, options); } - query = `CALL vn.ticketCalculateSale(?)`; + query = `CALL vn.sale_calculateComponent(?, NULL)`; await Self.rawSql(query, [sale.id], options); const origin = ctx.req.headers.origin; diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index bb833709e..c1081c4be 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -60,7 +60,7 @@ module.exports = Self => { quantity: quantity }); - await Self.rawSql('CALL vn.ticketCalculateSale(?)', [newSale.id]); + await Self.rawSql('CALL vn.sale_calculateComponent(?, NULL)', [newSale.id]); return models.Sale.findById(newSale.id, { include: { diff --git a/modules/ticket/front/locale/es.yml b/modules/ticket/front/locale/es.yml index b26a6d6fa..5cc2e115e 100644 --- a/modules/ticket/front/locale/es.yml +++ b/modules/ticket/front/locale/es.yml @@ -76,5 +76,5 @@ Tracking: Estados Sale checked: Control clientes Components: Componentes Sale tracking: Líneas preparadas -Photos: Fotos +Pictures: Fotos Log: Historial \ No newline at end of file diff --git a/modules/zone/front/create/index.html b/modules/zone/front/create/index.html index 332e8a9b8..07ac38477 100644 --- a/modules/zone/front/create/index.html +++ b/modules/zone/front/create/index.html @@ -50,7 +50,7 @@ diff --git a/modules/zone/front/create/locale/es.yml b/modules/zone/front/create/locale/es.yml index 7c1317ca7..4827ced37 100644 --- a/modules/zone/front/create/locale/es.yml +++ b/modules/zone/front/create/locale/es.yml @@ -1,3 +1,3 @@ Traveling days: Días de viaje -Closing hour (ETD): Hora de cierre (ETD) +Closing hour: Hora de cierre Bonus: Bonificación \ No newline at end of file diff --git a/modules/zone/front/descriptor/index.html b/modules/zone/front/descriptor/index.html index 58441d10d..8f6dd819b 100644 --- a/modules/zone/front/descriptor/index.html +++ b/modules/zone/front/descriptor/index.html @@ -30,7 +30,7 @@ - {{::zone.id}} {{::zone.name}} - {{::zone.agencyMode.name}} + {{::zone.agencyMode.name}} {{::zone.hour | date: 'HH:mm'}} {{::zone.price | currency: 'EUR':2}} diff --git a/modules/zone/front/summary/index.html b/modules/zone/front/summary/index.html index c2694da45..20f74916e 100644 --- a/modules/zone/front/summary/index.html +++ b/modules/zone/front/summary/index.html @@ -13,7 +13,7 @@
- Date: Thu, 23 Apr 2020 17:59:46 +0200 Subject: [PATCH 20/25] ticket.index modificar orden de las secciones --- .../01-componentRenameMismatchXImbalance.sql | 1 + .../10180-holyWeek/02-catalog_calculate.sql | 1 + .../02-sale_calculateComponent.sql | 72 +++++--- .../10180-holyWeek/02-ticketCalculateClon.sql | 76 ++++----- .../02-ticketCalculateSaleForcePrice2.sql | 61 ------- .../02-ticketComponentUpdateSale.sql | 154 ++++++++++++++++++ .../02-ticket_componentMakeUpdate.sql | 107 ++++++++++++ .../02-ticket_componentPreview.sql | 66 ++++---- .../02-ticket_priceDifference.sql | 50 ++++++ .../02-ticket_recalcComponents.sql | 94 ++++++----- .../02-ticket_recalcComponentsForcePrice.sql | 78 --------- ...02-ticket_recalcComponentsForcePrice__.sql | 2 + .../02-ticket_withoutComponents.sql | 72 ++++++++ .../03-ticketCalculateSaleForcePrice2__.sql | 2 + .../03-ticketCalculateSaleForcePrice__ .sql | 2 + ...eSale.sql => 03-ticketCalculateSale__.sql} | 7 +- .../03-ticket_componentUpdate__.sql | 83 ++++++++++ db/tests/vn/ticket_recalcComponents.spec.js | 2 +- .../methods/ticket/recalculateComponents.js | 2 +- modules/ticket/front/routes.json | 8 +- 20 files changed, 659 insertions(+), 281 deletions(-) create mode 100644 db/changes/10180-holyWeek/01-componentRenameMismatchXImbalance.sql delete mode 100644 db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice2.sql create mode 100644 db/changes/10180-holyWeek/02-ticketComponentUpdateSale.sql create mode 100644 db/changes/10180-holyWeek/02-ticket_componentMakeUpdate.sql create mode 100644 db/changes/10180-holyWeek/02-ticket_priceDifference.sql delete mode 100644 db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice.sql create mode 100644 db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice__.sql create mode 100644 db/changes/10180-holyWeek/02-ticket_withoutComponents.sql create mode 100644 db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice2__.sql create mode 100644 db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__ .sql rename db/changes/10180-holyWeek/{02-ticketCalculateSale.sql => 03-ticketCalculateSale__.sql} (92%) create mode 100644 db/changes/10180-holyWeek/03-ticket_componentUpdate__.sql diff --git a/db/changes/10180-holyWeek/01-componentRenameMismatchXImbalance.sql b/db/changes/10180-holyWeek/01-componentRenameMismatchXImbalance.sql new file mode 100644 index 000000000..34dd3be3c --- /dev/null +++ b/db/changes/10180-holyWeek/01-componentRenameMismatchXImbalance.sql @@ -0,0 +1 @@ +UPDATE `vn`.`component` SET `code` = 'imbalance' WHERE (`id` = '36'); diff --git a/db/changes/10180-holyWeek/02-catalog_calculate.sql b/db/changes/10180-holyWeek/02-catalog_calculate.sql index b18d85710..eeadb7241 100644 --- a/db/changes/10180-holyWeek/02-catalog_calculate.sql +++ b/db/changes/10180-holyWeek/02-catalog_calculate.sql @@ -131,6 +131,7 @@ proc: BEGIN JOIN ( SELECT MIN(price) price, itemFk, priceKg FROM tmp.ticketComponentPrice + WHERE warehouseFk = vWarehouseFk GROUP BY itemFk ) bl ON bl.itemFk = tl.itemFk WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk diff --git a/db/changes/10180-holyWeek/02-sale_calculateComponent.sql b/db/changes/10180-holyWeek/02-sale_calculateComponent.sql index 5158bd26c..a0a5f8833 100644 --- a/db/changes/10180-holyWeek/02-sale_calculateComponent.sql +++ b/db/changes/10180-holyWeek/02-sale_calculateComponent.sql @@ -10,8 +10,6 @@ proc: BEGIN * * @param vSale Delivery date * @param vOption indica en que componente pone el descuadre, NULL en casos habituales - * @return tmp.ticketLot(warehouseFk, available, itemFk, buyFk) - * @return tmp.sale(saleFk, warehouseFk) */ DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; @@ -20,27 +18,55 @@ proc: BEGIN DECLARE vTicket BIGINT; DECLARE vItem BIGINT; DECLARE vLanded DATE; - DECLARE vTicketFree BOOLEAN DEFAULT TRUE; + DECLARE vIsEditable BOOLEAN; DECLARE vZoneFk INTEGER; - SELECT NOT (t.refFk IS NOT NULL OR ts.alertLevel > 0) OR s.price = 0, s.ticketFk, s.itemFk , t.zoneFk - INTO vTicketFree, vTicket, vItem, vZoneFk - FROM vn.ticket t - JOIN vn.sale s ON s.ticketFk = t.id - LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id - WHERE s.id = vSale - LIMIT 1; - - SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM agencyMode a - JOIN ticket t ON t.agencyModeFk = a.id - WHERE t.id = vTicket; + SELECT t.refFk IS NULL AND (IFNULL(ts.alertLevel, 0) = 0 OR s.price = 0), + s.ticketFk, + s.itemFk , + t.zoneFk, + t.warehouseFk, + t.shipped, + t.addressFk, + t.agencyModeFk, + t.landed + INTO vIsEditable, + vTicket, + vItem, + vZoneFk, + vWarehouseFk, + vShipped, + vAddressFk, + vAgencyModeFk, + vLanded + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + WHERE s.id = vSale; - IF IFNULL(vZoneFk,0) = 0 THEN - CALL util.throw('ticket dont have zone'); - END IF; - + IF vLanded IS NULL OR vZoneFk IS NULL THEN + + CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + IF (SELECT COUNT(*) FROM tmp.zoneGetLanded LIMIT 1) = 0 THEN + CALL util.throw('There is no zone for these parameters'); + END IF; + + UPDATE ticket t + SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) + WHERE t.id = vTicketFk AND t.landed IS NULL; + + IF vZoneFk IS NULL THEN + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + UPDATE ticket t + SET t.zoneFk = vZoneFk + WHERE t.id = vTicketFk AND t.zoneFk IS NULL; + END IF; + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + END IF; + + -- rellena la tabla buyUltimate con la ultima compra CALL buyUltimate (vWarehouseFk, vShipped); DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; @@ -58,14 +84,14 @@ proc: BEGIN CREATE TEMPORARY TABLE tmp.sale (PRIMARY KEY (saleFk)) ENGINE = MEMORY SELECT vSale saleFk,vWarehouseFk warehouseFk; - + IF vOption IS NULL THEN - SET vOption = IF(vTicketFree, 1, 6); + SET vOption = IF(vIsEditable, 1, 6); END IF; CALL ticketComponentUpdateSale(vOption); - INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) + INSERT INTO ticketLog (originFk, userFk, `action`, description) VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); CALL catalog_componentPurge(); diff --git a/db/changes/10180-holyWeek/02-ticketCalculateClon.sql b/db/changes/10180-holyWeek/02-ticketCalculateClon.sql index bd44f592f..6c9518b3b 100644 --- a/db/changes/10180-holyWeek/02-ticketCalculateClon.sql +++ b/db/changes/10180-holyWeek/02-ticketCalculateClon.sql @@ -5,85 +5,87 @@ DELIMITER $$ USE `vn`$$ CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT) BEGIN - /* - * @vTicketNew id del nuevo ticket clonado - * @vTicketOld id ticket original, a partir del qual se clonara el nuevo - * Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo - */ +/* + * Recalcula los componentes un ticket clonado, + * las lineas a precio cero fuerza para que tengan precio, el resto lo respeta + * @param vTicketNew nuevo ticket clonado + * @param vTicketOld icket original, a partir del qual se clonara el nuevo +*/ DECLARE vShipped DATE; DECLARE vClient INT; DECLARE vWarehouse SMALLINT; - DECLARE vAgencyMode INT; - DECLARE vAddress INT; + DECLARE vAgencyMode INT; + DECLARE vAddress INT; DECLARE vLanded DATE; - DECLARE vAgency INT; - DECLARE vZoneFk INT; + DECLARE vAgency INT; + DECLARE vZoneFk INT; - REPLACE INTO orderTicket(orderFk,ticketFk) + REPLACE INTO orderTicket(orderFk,ticketFk) SELECT orderFk, vTicketNew FROM orderTicket WHERE ticketFk = vTicketOld; SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk - FROM vn.agencyMode a - JOIN vn.ticket t ON t.agencyModeFk = a.id - WHERE t.id = vTicketNew; + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicketNew; IF vLanded IS NULL THEN CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse); - UPDATE ticket t + UPDATE ticket t JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk SET t.landed = zgl.landed, t.zone = zgl.zoneFk WHERE t.id = vTicketNew; - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - END IF; - - -- rellena la tabla tmp.buyUltimate con la ultima compra - CALL buyUltimate(vWarehouse, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot + END IF; + + -- rellena la tabla tmp.buyUltimate con la ultima compra + CALL buyUltimate(vWarehouse, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk, vZoneFk zoneFk FROM sale s LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; - + CALL catalog_componentPrepare(); CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode, vWarehouse); - - -- Bionizamos lineas con Preu = 0 - DROP TEMPORARY TABLE IF EXISTS tmp.sale; + + -- Bionizamos lineas con Preu = 0 + DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale (PRIMARY KEY (saleFk)) ENGINE = MEMORY SELECT s.id saleFk, vWarehouse warehouseFk FROM sale s JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew AND s.price = 0; - + CALL ticketComponentUpdateSale(1); - - -- Bionizamos lineas con Preu > 0 + + -- Bionizamos lineas con Preu > 0 DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale (PRIMARY KEY (saleFk)) ENGINE = MEMORY SELECT s.id saleFk, vWarehouse warehouseFk FROM sale s JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew - AND s.price > 0; - + AND s.price > 0; + CALL ticketComponentUpdateSale(6); - + -- Log - CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); + CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); -- Limpieza - CALL catalog_componentPurge(); - DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE IF EXISTS + tmp.buyUltimate, + tmp.sale, + tmp.zoneGetLanded; END$$ diff --git a/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice2.sql b/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice2.sql deleted file mode 100644 index 89f4320f2..000000000 --- a/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice2.sql +++ /dev/null @@ -1,61 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCalculateSaleForcePrice2`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice2`(IN vSale BIGINT) -proc: BEGIN - - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vAddressFk INT; - DECLARE vTicket BIGINT; - DECLARE vItem BIGINT; - DECLARE vZoneFk INT; - - SELECT ticketFk, itemFk - INTO vTicket, vItem - FROM sale - WHERE id = vSale; - - SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk - INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk - FROM agencyMode a - JOIN ticket t ON t.agencyModeFk = a.id - WHERE t.id = vTicket; - - IF vZoneFk IS NULL THEN - CALL util.throw('ticket without zone'); - END IF; - - CALL buyUltimate (vWarehouseFk, vShipped); - - DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk, vZoneFk zoneFk - FROM tmp.buyUltimate - WHERE itemFk = vItem; - - CALL vn.catalog_componentCalculate; - CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT vSale saleFk,vWarehouseFk warehouseFk; - - CALL ticketComponentUpdateSale(1); - - INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) - VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.sale; - CALL catalog_componentPurge(); - -END$$ - -DELIMITER ; - diff --git a/db/changes/10180-holyWeek/02-ticketComponentUpdateSale.sql b/db/changes/10180-holyWeek/02-ticketComponentUpdateSale.sql new file mode 100644 index 000000000..b58189ae6 --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticketComponentUpdateSale.sql @@ -0,0 +1,154 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketComponentUpdateSale`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentUpdateSale`(vOption INT) +BEGIN +/** + * A partir de la tabla tmp.sale, crea los Movimientos_componentes + * y modifica el campo Preu de la tabla Movimientos + * + * @param i_option integer tipo de actualizacion + * @param table tmp.sale tabla memory con el campo saleFk, warehouseFk + **/ + DECLARE vComponentFk INT; + DECLARE vRenewComponents BOOLEAN; + DECLARE vKeepPrices BOOLEAN; + + CASE vOption + WHEN 1 THEN + SET vRenewComponents = TRUE; + SET vKeepPrices = FALSE; + WHEN 2 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection'; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + WHEN 3 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana'; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + WHEN 4 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount'; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + /* WHEN 5 THEN + SET vComponentFk = 35; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE;*/ + WHEN 6 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'imbalance'; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + WHEN 7 THEN + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk NOT IN (28, 29) + GROUP BY s.id; + + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk NOT IN (28, 29) + GROUP BY s.id; + + SET vRenewComponents = FALSE; + SET vKeepPrices = FALSE; + WHEN 8 THEN + DELETE sc.* + FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk; + + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id; + + SET vRenewComponents = FALSE; + SET vKeepPrices = FALSE; + WHEN 9 THEN + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + END CASE; + + IF vRenewComponents THEN + DELETE sc.* + FROM tmp.sale tmps + JOIN saleComponent sc ON sc.saleFk = tmps.saleFk + JOIN `component` c ON c.id = sc.componentFk + WHERE c.isRenewable; + + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, tc.componentFk, tc.cost + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = tc.componentFk + LEFT JOIN `component` c ON c.id = tc.componentFk + WHERE IF(sc.componentFk IS NULL AND NOT c.isRenewable, FALSE, TRUE); + END IF; + + IF vKeepPrices THEN + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, vComponentFk, ROUND((s.price * (100 - s.discount) / 100) - SUM(sc.value), 3) dif + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + WHERE sc.saleFk <> vComponentFk + GROUP BY s.id + HAVING dif <> 0; + ELSE + UPDATE sale s + JOIN item i on i.id = s.itemFk + JOIN itemType it on it.id = i.typeFk + JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk + FROM saleComponent sc + JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk + GROUP BY sc.saleFk) sc ON sc.saleFk = s.id + SET s.price = sumValue + WHERE it.code != 'PRT' ; + + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, 21, ROUND((s.price * (100 - s.discount) / 100) - SUM(value), 3) saleValue + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + WHERE sc.componentFk != 21 + GROUP BY s.id + HAVING ROUND(saleValue, 4) <> 0; + END IF; + + UPDATE sale s + JOIN ( + SELECT SUM(sc.value) sumValue, sc.saleFk + FROM saleComponent sc + JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk + JOIN `component` c ON c.id = sc.componentFk + JOIN componentType ct on ct.id = c.typeFk AND ct.isBase + GROUP BY sc.saleFk) sc ON sc.saleFk = s.id + SET s.priceFixed = sumValue, s.isPriceFixed = 1; + + DELETE sc.* + FROM saleComponent sc + JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk + JOIN sale s on s.id = sc.saleFk + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE it.code = 'PRT'; + + INSERT INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, 15, s.price + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + JOIN item i ON i.id = s.itemFK + JOIN itemType it ON it.id = i.typeFk + WHERE it.code = 'PRT' AND s.price > 0; +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-ticket_componentMakeUpdate.sql b/db/changes/10180-holyWeek/02-ticket_componentMakeUpdate.sql new file mode 100644 index 000000000..7fdf3f193 --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticket_componentMakeUpdate.sql @@ -0,0 +1,107 @@ +USE `vn`; +DROP procedure IF EXISTS `ticket_componentMakeUpdate`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentMakeUpdate`( + vTicketFk INT, + vClientFk INT, + vAgencyModeFk INT, + vAddressFk INT, + vZoneFk INT, + vWarehouseFk TINYINT, + vCompanyFk SMALLINT, + vShipped DATETIME, + vLanded DATE, + vIsDeleted BOOLEAN, + vHasToBeUnrouted BOOLEAN, + vOption INT) +BEGIN +/** + * Modifica en el ticket los campos que se le pasan por parámetro + * y cambia sus componentes + * + * @param vTicketFk Id del ticket a modificar + * @param vClientFk nuevo cliente + * @param vAgencyModeFk nueva agencia + * @param vAddressFk nuevo consignatario + * @param vZoneFk nueva zona + * @param vWarehouseFk nuevo almacen + * @param vCompanyFk nueva empresa + * @param vShipped nueva fecha del envio de mercancia + * @param vLanded nueva fecha de recepcion de mercancia + * @param vIsDeleted si se borra el ticket + * @param vHasToBeUnrouted si se le elimina la ruta al ticket + * @param vOption opcion para el case del proc ticketComponentUpdateSale + */ + DECLARE vPrice DECIMAL(10,2); + DECLARE vBonus DECIMAL(10,2); + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); + + START TRANSACTION; + + IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN + + UPDATE ticket t + JOIN address a ON a.id = vAddressFk + SET t.nickname = a.nickname + WHERE t.id = vTicketFk; + + END IF; + + CALL zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); + + SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus + FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + UPDATE ticket t + SET + t.clientFk = vClientFk, + t.agencyModeFk = vAgencyModeFk, + t.addressFk = vAddressFk, + t.zoneFk = vZoneFk, + t.zonePrice = vPrice, + t.zoneBonus = vBonus, + t.warehouseFk = vWarehouseFk, + t.companyFk = vCompanyFk, + t.landed = vLanded, + t.shipped = vShipped, + t.isDeleted = vIsDeleted + WHERE + t.id = vTicketFk; + + IF vHasToBeUnrouted THEN + UPDATE ticket t SET t.routeFk = NULL + WHERE t.id = vTicketFk; + END IF; + + IF vOption <> 8 THEN + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) + ENGINE = MEMORY + SELECT id AS saleFk, vWarehouseFk warehouseFk + FROM sale s WHERE s.ticketFk = vTicketFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + CREATE TEMPORARY TABLE tmp.ticketComponent + SELECT * FROM tmp.ticketComponentPreview; + + CALL ticketComponentUpdateSale (vOption); + + DROP TEMPORARY TABLE tmp.sale; + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + END IF; + COMMIT; + + DROP TEMPORARY TABLE tmp.zoneGetShipped, tmp.ticketComponentPreview; +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10180-holyWeek/02-ticket_componentPreview.sql b/db/changes/10180-holyWeek/02-ticket_componentPreview.sql index bec56025d..d69435bb7 100644 --- a/db/changes/10180-holyWeek/02-ticket_componentPreview.sql +++ b/db/changes/10180-holyWeek/02-ticket_componentPreview.sql @@ -19,63 +19,60 @@ BEGIN * @param vZoneFk nueva zona * @param vWarehouseFk nuevo warehouse * - * @return tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + * @return tmp.ticketComponentPreview (warehouseFk, itemFk, componentFk, cost) */ - DECLARE vShipped DATE; - DECLARE vBuyOrderItem INT DEFAULT 100; + DECLARE vHasDataChanged BOOL DEFAULT FALSE; + DECLARE vHasAddressChanged BOOL; + DECLARE vHasZoneChanged BOOL DEFAULT FALSE; + DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE; - DECLARE vHasDataChanged BOOL DEFAULT FALSE; - DECLARE vHasAddressChanged BOOL; - DECLARE vHasZoneChanged BOOL DEFAULT FALSE; - DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE; - + DECLARE vShipped DATE; DECLARE vAddressTypeRateFk INT DEFAULT NULL; DECLARE vAgencyModeTypeRateFk INT DEFAULT NULL; - - DECLARE vHasChangeAll BOOL DEFAULT FALSE; - + + DECLARE vHasChangeAll BOOL DEFAULT FALSE; + SELECT DATE(landed) <> vLanded, addressFk <> vAddressFk, zoneFk <> vZoneFk, - warehouseFk <> vWarehouseFk + warehouseFk <> vWarehouseFk INTO vHasDataChanged, - vHasAddressChanged, - vHasZoneChanged, - vHasWarehouseChanged + vHasAddressChanged, + vHasZoneChanged, + vHasWarehouseChanged FROM vn.ticket t - WHERE t.id = vTicketFk; + WHERE t.id = vTicketFk; - IF vHasDataChanged OR vHasWarehouseChanged THEN + IF vHasDataChanged OR vHasWarehouseChanged THEN SET vHasChangeAll = TRUE; END IF; - + IF vHasAddressChanged THEN SET vAddressTypeRateFk = 5; - END IF; - + END IF; + IF vHasZoneChanged THEN SET vAgencyModeTypeRateFk = 6; - END IF; + END IF; SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped FROM zone WHERE id = vZoneFk; - + CALL buyUltimate(vWarehouseFk, vShipped); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( + CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( SELECT vWarehouseFk AS warehouseFk, NULL AS available, s.itemFk, bu.buyFk, - vZoneFk zoneFk + vZoneFk zoneFk FROM sale s LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk WHERE s.ticketFk = vTicketFk - AND s.itemFk != vBuyOrderItem GROUP BY bu.warehouseFk, bu.itemFk); CALL catalog_componentPrepare(); @@ -92,21 +89,22 @@ BEGIN OR (NOT vHasChangeAll AND (NOT (c.typeFk <=> vAddressTypeRateFk - OR c.typeFk <=> vAgencyModeTypeRateFk)))); + OR c.typeFk <=> vAgencyModeTypeRateFk)))); - SET @shipped = vShipped; + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPreview; + CREATE TEMPORARY TABLE tmp.ticketComponentPreview + SELECT * FROM tmp.ticketComponent; - DROP TEMPORARY TABLE - tmp.buyUltimate, - tmp.ticketLot; + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE tmp.buyUltimate; IF vShipped IS NULL THEN CALL util.throw('NO_ZONE_AVAILABLE'); - END IF; - + END IF; + IF vShipped < CURDATE() THEN CALL util.throw('ERROR_PAST_SHIPMENT'); - END IF; + END IF; END$$ DELIMITER ; diff --git a/db/changes/10180-holyWeek/02-ticket_priceDifference.sql b/db/changes/10180-holyWeek/02-ticket_priceDifference.sql new file mode 100644 index 000000000..b80ea7f88 --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticket_priceDifference.sql @@ -0,0 +1,50 @@ +USE `vn`; +DROP procedure IF EXISTS `ticket_priceDifference`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_priceDifference`( + vTicketFk INT, + vLanded DATE, + vAddressFk INT, + vZoneFk INT, + vWarehouseFk INT) +BEGIN +/** + * Devuelve las diferencias de precio de los movimientos de un ticket. + * + * @param vTicketFk Id del ticket + * @param vLanded Fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vZoneFk Id de la zona + * @param vWarehouseFk Id del almacén + */ + CALL vn.ticket_componentPreview(vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); + + SELECT s.itemFk, + i.name, + i.size, + i.category, + IFNULL(s.quantity, 0) AS quantity, + IFNULL(s.price, 0) AS price, + ROUND(SUM(tc.cost), 2) AS newPrice, + s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference, + s.id AS saleFk + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk + AND tc.warehouseFk = t.warehouseFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = tc.componentFk + LEFT JOIN `component` c ON c.id = tc.componentFk + WHERE t.id = vTicketFk + AND IF(sc.componentFk IS NULL + AND c.classRate IS NOT NULL, FALSE, TRUE) + GROUP BY s.id ORDER BY s.id; + + DROP TEMPORARY TABLE tmp.ticketComponentPreview; +END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/02-ticket_recalcComponents.sql b/db/changes/10180-holyWeek/02-ticket_recalcComponents.sql index eb124ffdb..9ac4942f9 100644 --- a/db/changes/10180-holyWeek/02-ticket_recalcComponents.sql +++ b/db/changes/10180-holyWeek/02-ticket_recalcComponents.sql @@ -3,37 +3,64 @@ DROP procedure IF EXISTS `ticket_recalcComponents`; DELIMITER $$ USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT ) +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN) proc: BEGIN /** - * Este procedimiento trata de "rebionizar" un ticket, + * Este procedimiento recalcula los componentes de un ticket, * eliminando los componentes existentes e insertandolos de nuevo * * @param vTicketFk Id del ticket - * @return tmp.buyUltimate + * @param vIsTicketEditable si no se quiere forzar llamar con NULL */ DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; DECLARE vAddressFk INT; DECLARE vLanded DATE; - DECLARE vIsTicketEditable BOOLEAN; DECLARE vZoneFk INTEGER; - - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk + + IF vIsTicketEditable IS NULL THEN + SELECT IFNULL(ts.alertLevel,0) = 0 AND IFNULL(t.refFk,'') = '' + INTO vIsTicketEditable + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + END IF; + + SELECT t.warehouseFk, + t.shipped, + t.addressFk, + t.agencyModeFk, + t.landed, + t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded, vZoneFk FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; + WHERE t.id = vTicketFk; + + IF vLanded IS NULL OR vZoneFk IS NULL THEN + + CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + IF (SELECT COUNT(*) FROM tmp.zoneGetLanded LIMIT 1) = 0 THEN + CALL util.throw('There is no zone for these parameters'); + END IF; + + UPDATE ticket t + SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) + WHERE t.id = vTicketFk AND t.landed IS NULL; + + IF vZoneFk IS NULL THEN + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + UPDATE ticket t + SET t.zoneFk = vZoneFk + WHERE t.id = vTicketFk AND t.zoneFk IS NULL; + END IF; + DROP TEMPORARY TABLE tmp.zoneGetLanded; - CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); - - CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + END IF; + + -- rellena la tabla buyUltimate con la ultima compra + CALL buyUltimate (vWarehouseFk, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot @@ -45,33 +72,22 @@ proc: BEGIN GROUP BY s.itemFk; CALL catalog_componentPrepare(); - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); - + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + -- si el ticket esta facturado, respeta los precios + CALL ticketComponentUpdateSale(IF(vIsTicketEditable, 1, 6)); - IF vLanded IS NULL THEN - - CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE + tmp.buyUltimate, + tmp.sale; END$$ DELIMITER ; diff --git a/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice.sql b/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice.sql deleted file mode 100644 index 944490d20..000000000 --- a/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice.sql +++ /dev/null @@ -1,78 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticket_recalcComponentsForcePrice`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN ) -proc: BEGIN - -/** - * Este procedimiento trata de "rebionizar" un ticket, - * eliminando los componentes existentes e insertandolos de nuevo - * - * @param vTicketFk Id del ticket - * @return tmp.buyUltimate - */ - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vAgencyModeFk INT; - DECLARE vAddressFk INT; - DECLARE vLanded DATE; - DECLARE vZoneFk INTEGER; - - IF vIsTicketEditable IS NULL THEN - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk - FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - END IF; - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; - - CALL zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, TRUE); - - CALL buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk, vZoneFk zoneFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketFk - GROUP BY s.itemFk; - - CALL catalog_componentPrepare(); - CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios - - IF vLanded IS NULL THEN - - CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; -END$$ - -DELIMITER ; - diff --git a/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice__.sql b/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice__.sql new file mode 100644 index 000000000..995bfbfcd --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice__.sql @@ -0,0 +1,2 @@ +USE `vn`; +DROP procedure IF EXISTS `ticket_recalcComponentsForcePrice`; diff --git a/db/changes/10180-holyWeek/02-ticket_withoutComponents.sql b/db/changes/10180-holyWeek/02-ticket_withoutComponents.sql new file mode 100644 index 000000000..de789b956 --- /dev/null +++ b/db/changes/10180-holyWeek/02-ticket_withoutComponents.sql @@ -0,0 +1,72 @@ +USE `vn`; +DROP procedure IF EXISTS `ticket_withoutComponents`; +DROP procedure IF EXISTS `ticket_checkNoComponents`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_checkNoComponents`(vShippedFrom DATETIME, vShippedTo DATETIME) +BEGIN + +/** + * Comprueba que los tickets entre un rango de fechas tienen componentes + * + * @param vDatedFrom Id del ticket + * @param vIsTicketEditable si no se quiere forzar llamar con NULL + */ + DECLARE v_done BOOL DEFAULT FALSE; + DECLARE vSaleFk INTEGER; + DECLARE vCur CURSOR FOR + SELECT s.id + FROM ticket t + JOIN client clt ON clt.id = t.clientFk + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType tp ON tp.id = i.typeFk + JOIN itemCategory ic ON ic.id = tp.categoryFk + LEFT JOIN tmp.coste c ON c.id = s.id + WHERE t.shipped >= vDatedFrom AND t.shipped <= vDatedTo + AND c.id IS NULL + AND clt.isActive != 0 + AND ic.merchandise != 0 + GROUP BY s.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET v_done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.coste; + + DROP TEMPORARY TABLE IF EXISTS tmp.coste; + CREATE TEMPORARY TABLE tmp.coste + (primary key (id)) ENGINE = MEMORY + SELECT s.id + FROM ticket t + JOIN client clt ON clt.id = t.clientFk + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType tp ON tp.id = i.typeFk + JOIN itemCategory ic ON ic.id = tp.categoryFk + JOIN saleComponent sc ON sc.saleFk = s.id + JOIN component c ON c.id = sc.componentFk + JOIN componentType ct ON ct.id = c.typeFk AND ct.id = 1 + WHERE t.shipped >= vDatedFrom + AND ic.merchandise != 0; + + OPEN vCur; + + l: LOOP + SET v_done = FALSE; + FETCH vCur INTO vSaleFk; + + IF v_done THEN + LEAVE l; + END IF; + + CALL sale_calculateComponent(vSaleFk, 1); + END LOOP; + + CLOSE vCur; + DROP TEMPORARY TABLE tmp.coste; + END$$ + +DELIMITER ; + diff --git a/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice2__.sql b/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice2__.sql new file mode 100644 index 000000000..a880135ba --- /dev/null +++ b/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice2__.sql @@ -0,0 +1,2 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketCalculateSaleForcePrice2`; \ No newline at end of file diff --git a/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__ .sql b/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__ .sql new file mode 100644 index 000000000..d7eb5d32b --- /dev/null +++ b/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__ .sql @@ -0,0 +1,2 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketCalculateSaleForcePrice`; \ No newline at end of file diff --git a/db/changes/10180-holyWeek/02-ticketCalculateSale.sql b/db/changes/10180-holyWeek/03-ticketCalculateSale__.sql similarity index 92% rename from db/changes/10180-holyWeek/02-ticketCalculateSale.sql rename to db/changes/10180-holyWeek/03-ticketCalculateSale__.sql index aea966ed1..acefc29d5 100644 --- a/db/changes/10180-holyWeek/02-ticketCalculateSale.sql +++ b/db/changes/10180-holyWeek/03-ticketCalculateSale__.sql @@ -1,9 +1,10 @@ USE `vn`; DROP procedure IF EXISTS `ticketCalculateSale`; +DROP procedure IF EXISTS `ticketCalculateSale__`; DELIMITER $$ USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSale`(IN vSale BIGINT) +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSale__`(IN vSale BIGINT) proc: BEGIN -- OBSOLETO USAR: sale_calculateComponent(vSale, NULL) DECLARE vShipped DATE; @@ -57,10 +58,10 @@ proc: BEGIN INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + CALL catalog_componentPurge(); DROP TEMPORARY TABLE tmp.buyUltimate; DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CALL catalog_componentPurge(); - + END$$ DELIMITER ; diff --git a/db/changes/10180-holyWeek/03-ticket_componentUpdate__.sql b/db/changes/10180-holyWeek/03-ticket_componentUpdate__.sql new file mode 100644 index 000000000..f75f157e8 --- /dev/null +++ b/db/changes/10180-holyWeek/03-ticket_componentUpdate__.sql @@ -0,0 +1,83 @@ +USE `vn`; +DROP procedure IF EXISTS `vn`.`ticket_componentUpdate`; +DROP procedure IF EXISTS `vn`.`ticket_componentUpdate__`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentUpdate__`( + vTicketFk INT, + vClientFk INT, + vAgencyModeFk INT, + vAddressFk INT, + vZoneFk INT, + vWarehouseFk TINYINT, + vCompanyFk SMALLINT, + vShipped DATETIME, + vLanded DATE, + vIsDeleted BOOLEAN, + vHasToBeUnrouted BOOLEAN, + vOption INT) +BEGIN + DECLARE vPrice DECIMAL(10,2); + DECLARE vBonus DECIMAL(10,2); + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN + + UPDATE ticket t + JOIN address a ON a.id = vAddressFk + SET t.nickname = a.nickname + WHERE t.id = vTicketFk; + + END IF; + + CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); + + SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus + FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + UPDATE ticket t + SET + t.clientFk = vClientFk, + t.agencyModeFk = vAgencyModeFk, + t.addressFk = vAddressFk, + t.zoneFk = vZoneFk, + t.zonePrice = vPrice, + t.zoneBonus = vBonus, + t.warehouseFk = vWarehouseFk, + t.companyFk = vCompanyFk, + t.landed = vLanded, + t.shipped = vShipped, + t.isDeleted = vIsDeleted + WHERE + t.id = vTicketFk; + + IF vHasToBeUnrouted THEN + UPDATE ticket t SET t.routeFk = NULL + WHERE t.id = vTicketFk; + END IF; + + IF vOption <> 8 THEN + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) + ENGINE = MEMORY + SELECT id AS saleFk, vWarehouseFk warehouseFk + FROM sale s WHERE s.ticketFk = vTicketFk; + + CALL ticketComponentUpdateSale (vOption); + + DROP TEMPORARY TABLE tmp.sale; + END IF; + COMMIT; +END$$ + +DELIMITER ; +; diff --git a/db/tests/vn/ticket_recalcComponents.spec.js b/db/tests/vn/ticket_recalcComponents.spec.js index e140db34c..1256528e6 100644 --- a/db/tests/vn/ticket_recalcComponents.spec.js +++ b/db/tests/vn/ticket_recalcComponents.spec.js @@ -24,7 +24,7 @@ describe('ticket_recalcComponents()', () => { let modifiedSales = stmts.push(stmt) - 1; - stmt = new ParameterizedSQL('CALL vn.ticket_recalcComponents(?)', [ + stmt = new ParameterizedSQL('CALL vn.ticket_recalcComponents(?, NULL)', [ ticketId, ]); stmts.push(stmt); diff --git a/modules/ticket/back/methods/ticket/recalculateComponents.js b/modules/ticket/back/methods/ticket/recalculateComponents.js index 81fee4d70..0648983c5 100644 --- a/modules/ticket/back/methods/ticket/recalculateComponents.js +++ b/modules/ticket/back/methods/ticket/recalculateComponents.js @@ -26,6 +26,6 @@ module.exports = Self => { if (!isEditable) throw new UserError(`The current ticket can't be modified`); - return Self.rawSql('CALL vn.ticket_recalcComponents(?)', [id]); + return Self.rawSql('CALL vn.ticket_recalcComponents(?, NULL)', [id]); }; }; diff --git a/modules/ticket/front/routes.json b/modules/ticket/front/routes.json index d95788036..6f54a8efd 100644 --- a/modules/ticket/front/routes.json +++ b/modules/ticket/front/routes.json @@ -12,18 +12,18 @@ "card": [ {"state": "ticket.card.basicData.stepOne", "icon": "settings"}, {"state": "ticket.card.sale", "icon": "icon-lines"}, + {"state": "ticket.card.request.index", "icon": "icon-100"}, + {"state": "ticket.card.tracking.index", "icon": "remove_red_eye"}, + {"state": "ticket.card.log", "icon": "history"}, {"state": "ticket.card.observation", "icon": "insert_drive_file"}, + {"state": "ticket.card.picture", "icon": "image"}, {"state": "ticket.card.volume", "icon": "icon-volume"}, {"state": "ticket.card.expedition", "icon": "icon-package"}, {"state": "ticket.card.service", "icon": "icon-services"}, {"state": "ticket.card.package", "icon": "icon-bucket"}, - {"state": "ticket.card.tracking.index", "icon": "remove_red_eye"}, {"state": "ticket.card.saleChecked", "icon": "assignment"}, {"state": "ticket.card.components", "icon": "icon-components"}, {"state": "ticket.card.saleTracking", "icon": "assignment"}, - {"state": "ticket.card.picture", "icon": "image"}, - {"state": "ticket.card.log", "icon": "history"}, - {"state": "ticket.card.request.index", "icon": "icon-100"}, {"state": "ticket.card.dms.index", "icon": "cloud_download"} ] }, From ceb3d1f4cf9e25e54fed2aff26cfa58a1d6128bf Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 30 Apr 2020 07:20:43 +0200 Subject: [PATCH 21/25] all filters tested --- db/changes/10180-holyWeek/03-ekt_load.sql | 156 ++++++++++++++++++ front/core/directives/specs/dialog.spec.js | 5 +- front/core/filters/specs/currency.spec.js | 34 +--- .../core/filters/specs/dash-if-empty.spec.js | 20 +++ front/core/filters/specs/percentage.spec.js | 20 +++ front/core/filters/specs/phone.spec.js | 20 +++ front/core/filters/specs/ucwords.spec.js | 20 +++ front/core/filters/specs/zero-fill.spec.js | 24 +++ 8 files changed, 270 insertions(+), 29 deletions(-) create mode 100644 db/changes/10180-holyWeek/03-ekt_load.sql create mode 100644 front/core/filters/specs/dash-if-empty.spec.js create mode 100644 front/core/filters/specs/percentage.spec.js create mode 100644 front/core/filters/specs/phone.spec.js create mode 100644 front/core/filters/specs/ucwords.spec.js create mode 100644 front/core/filters/specs/zero-fill.spec.js diff --git a/db/changes/10180-holyWeek/03-ekt_load.sql b/db/changes/10180-holyWeek/03-ekt_load.sql new file mode 100644 index 000000000..0c83569b8 --- /dev/null +++ b/db/changes/10180-holyWeek/03-ekt_load.sql @@ -0,0 +1,156 @@ +CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT) +BEGIN + DECLARE vRef INT; + DECLARE vBuy INT; + DECLARE vItem INT; + DECLARE vQty INT; + DECLARE vPackage INT; + DECLARE vIsLot BOOLEAN; + DECLARE vForceToPacking INT DEFAULT 2; + + -- Carga los datos necesarios del EKT + + SELECT ref, qty, package INTO vRef, vQty, vPackage + FROM ekt e + LEFT JOIN item i ON e.ref = i.id + WHERE e.id = vSelf; + + -- Inserta el cubo si no existe + + IF vPackage = 800 + THEN + SET vPackage = 800 + vQty; + + INSERT IGNORE INTO vn2008.Cubos SET + Id_Cubo = vPackage, + x = 7200 / vQty, + y = 1; + ELSE + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) + SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) + FROM bucket WHERE bucket_id = vPackage; + + IF ROW_COUNT() > 0 + THEN + INSERT INTO vn2008.mail SET + `subject` = 'Cubo añadido', + `text` = CONCAT('Se ha añadido el cubo: ', vPackage), + `to` = 'ekt@verdnatura.es'; + END IF; + END IF; + + -- Intenta obtener el artículo en base a los atributos holandeses + + INSERT IGNORE INTO item_track SET + item_id = vRef; + + SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem + FROM vn2008.buy_edi e + JOIN item_track t ON t.item_id = e.ref + LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref + LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id + JOIN vn2008.config cfg + WHERE e.id = vSelf + AND l.id != vSelf + AND c.Id_Article != cfg.generic_item + AND IF(t.s1, l.s1 = e.s1, TRUE) + AND IF(t.s2, l.s2 = e.s2, TRUE) + AND IF(t.s3, l.s3 = e.s3, TRUE) + AND IF(t.s4, l.s4 = e.s4, TRUE) + AND IF(t.s5, l.s5 = e.s5, TRUE) + AND IF(t.s6, l.s6 = e.s6, TRUE) + AND IF(t.kop, l.kop = e.kop, TRUE) + AND IF(t.pac, l.pac = e.pac, TRUE) + AND IF(t.cat, l.cat = e.cat, TRUE) + AND IF(t.ori, l.ori = e.ori, TRUE) + AND IF(t.pro, l.pro = e.pro, TRUE) + AND IF(t.sub, l.sub = e.sub, TRUE) + AND IF(t.package, l.package = e.package, TRUE) + AND c.Id_Article < 170000 + ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; + + -- Determina si el articulo se vende por lotes + + IF vItem + THEN + SELECT COUNT(*) > 0 INTO vIsLot + FROM vn2008.Articles a + LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id + WHERE a.Id_Article = vItem + AND t.`transaction`; + + -- Si el articulo se vende por lotes se inserta un nuevo artículo + + IF vIsLot + THEN + INSERT INTO vn2008.Articles ( + Article + ,Medida + ,Categoria + ,Id_Origen + ,iva_group_id + ,Foto + ,Color + ,Codintrastat + ,tipo_id + ,Tallos + ) + SELECT + i.`name` + ,IFNULL(e.s1, e.pac) + ,e.cat + ,IFNULL(o.id, 17) + ,IFNULL(a.iva_group_id, 1) + ,a.Foto + ,a.Color + ,a.Codintrastat + ,IFNULL(a.tipo_id, 10) + ,IF(a.tipo_id = 15, 0, 1) + FROM vn2008.buy_edi e + LEFT JOIN item i ON i.id = e.ref + LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori + LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem + WHERE e.id = vSelf; + + SET vItem = LAST_INSERT_ID(); + END IF; + END IF; + + -- Inserta la compra asociada al EKT + + INSERT INTO vn2008.Compres + ( + Id_Entrada + ,buy_edi_id + ,Costefijo + ,Id_Article + ,`grouping` + ,caja + ,Packing + ,Cantidad + ,Productor + ,Etiquetas + ,Id_Cubo + ,`weight` + ) + SELECT + cfg.edi_entry + ,vSelf + ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri + ,IFNULL(vItem, cfg.generic_item) + ,IFNULL(c.`grouping`, e.pac) + ,vForceToPacking + ,@pac := e.pac / @t + ,@pac * e.qty + ,s.company_name + ,e.qty + ,IFNULL(c.Id_Cubo, e.package) + ,a.density * (vn.item_getVolume(a.Id_Article, IFNULL(c.Id_Cubo, e.package)) / 1000000) + FROM vn2008.buy_edi e + LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy + LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article + LEFT JOIN supplier s ON e.pro = s.supplier_id + JOIN vn2008.config cfg + WHERE e.id = vSelf + LIMIT 1; +END \ No newline at end of file diff --git a/front/core/directives/specs/dialog.spec.js b/front/core/directives/specs/dialog.spec.js index fe84cdcc7..e43fca7cf 100644 --- a/front/core/directives/specs/dialog.spec.js +++ b/front/core/directives/specs/dialog.spec.js @@ -1,5 +1,4 @@ describe('Directive dialog', () => { - let $scope; let $element; let element; let compile; @@ -9,7 +8,7 @@ describe('Directive dialog', () => { compile = _element => { inject(($compile, $rootScope) => { - $scope = $rootScope.$new(); + let $scope = $rootScope.$new(); $scope.myDialog = controller; element = angular.element(_element); $compile(element)($scope); @@ -17,7 +16,7 @@ describe('Directive dialog', () => { }); }; - beforeEach(angular.mock.inject(($rootScope, $compile) => { + beforeEach(inject(($rootScope, $compile) => { $element = $compile('')($rootScope); controller = $element.controller('vnDialog'); })); diff --git a/front/core/filters/specs/currency.spec.js b/front/core/filters/specs/currency.spec.js index 28a4a3640..ecb94efe0 100644 --- a/front/core/filters/specs/currency.spec.js +++ b/front/core/filters/specs/currency.spec.js @@ -1,41 +1,23 @@ describe('Currency filter', () => { - let compile; - let $element; - beforeEach(ngModule('vnCore')); - - compile = html => { - inject(($compile, $rootScope) => { - $element = $compile(html)($rootScope); - $rootScope.$digest(); - }); - }; + let currencyFilter; + beforeEach(inject(_currencyFilter_ => { + currencyFilter = _currencyFilter_; + })); it('should return a ONE decimal number as per the argument', () => { - let html = `
{{200 | currency: 'EUR': 1}}
`; - compile(html); - - expect($element[0].innerHTML).toContain('200.0'); + expect(currencyFilter(200, 'EUR', 1)).toContain('200.0'); }); it('should return a TWO decimals number as per the argument', () => { - let html = `
{{200 | currency: 'EUR': 2}}
`; - compile(html); - - expect($element[0].innerHTML).toContain('200.00'); + expect(currencyFilter(200, 'EUR', 2)).toContain('200.00'); }); it('should return a TEN decimals number as per the argument', () => { - let html = `
{{200 | currency: 'EUR': 10}}
`; - compile(html); - - expect($element[0].innerHTML).toContain('200.0000000000'); + expect(currencyFilter(200, 'EUR', 10)).toContain('200.0000000000'); }); it('sould return nothing when the value is not set', () => { - let html = `
{{null | currency: 'EUR': 2}}
`; - compile(html); - - expect($element[0].innerHTML).toEqual(''); + expect(currencyFilter(null, 'EUR', 2)).toBeUndefined(); }); }); diff --git a/front/core/filters/specs/dash-if-empty.spec.js b/front/core/filters/specs/dash-if-empty.spec.js new file mode 100644 index 000000000..51e2222ca --- /dev/null +++ b/front/core/filters/specs/dash-if-empty.spec.js @@ -0,0 +1,20 @@ +'use strict'; +describe('Dash-if-empty filter', () => { + beforeEach(ngModule('vnCore')); + let dashIfEmptyFilter; + beforeEach(inject(_dashIfEmptyFilter_ => { + dashIfEmptyFilter = _dashIfEmptyFilter_; + })); + + it('should return a dash if input is null', () => { + expect(dashIfEmptyFilter(null)).toBe('-'); + }); + + it('should return a dash if input is empty', () => { + expect(dashIfEmptyFilter('')).toBe('-'); + }); + + it('should return same input is there is something', () => { + expect(dashIfEmptyFilter('something')).toBe('something'); + }); +}); diff --git a/front/core/filters/specs/percentage.spec.js b/front/core/filters/specs/percentage.spec.js new file mode 100644 index 000000000..8961dc1ee --- /dev/null +++ b/front/core/filters/specs/percentage.spec.js @@ -0,0 +1,20 @@ +'use strict'; +describe('Percentage filter', () => { + beforeEach(ngModule('vnCore')); + + it('should return null for input null', () => { + expect(percentageFilter(null, null)).toBeNull(); + }); + + it('should return null for input empty', () => { + expect(percentageFilter('', 2)).toBeNull(); + }); + + it('should return a TWO decimals number', () => { + expect(percentageFilter(0, 2)).toBe('0.00%'); + }); + + it('should return zero decimals number', () => { + expect(percentageFilter(0.5, 0)).toBe('50%'); + }); +}); diff --git a/front/core/filters/specs/phone.spec.js b/front/core/filters/specs/phone.spec.js new file mode 100644 index 000000000..fdff2556c --- /dev/null +++ b/front/core/filters/specs/phone.spec.js @@ -0,0 +1,20 @@ +'use strict'; +describe('Phone filter', () => { + beforeEach(ngModule('vnCore')); + let phoneFilter; + beforeEach(inject(_phoneFilter_ => { + phoneFilter = _phoneFilter_; + })); + + it('should return empty string for input null', () => { + expect(phoneFilter(null)).toBe(''); + }); + + it('should return empty stringfor input empty', () => { + expect(phoneFilter('')).toBe(''); + }); + + it('should format putting a space every three digits', () => { + expect(phoneFilter('999999999')).toBe('999 999 999 '); + }); +}); diff --git a/front/core/filters/specs/ucwords.spec.js b/front/core/filters/specs/ucwords.spec.js new file mode 100644 index 000000000..640bcc0e4 --- /dev/null +++ b/front/core/filters/specs/ucwords.spec.js @@ -0,0 +1,20 @@ +'use strict'; +describe('Ucwords filter', () => { + beforeEach(ngModule('vnCore')); + let ucwordsFilter; + beforeEach(inject(_ucwordsFilter_ => { + ucwordsFilter = _ucwordsFilter_; + })); + + it('should return empty string for input null', () => { + expect(ucwordsFilter(null)).toBe(''); + }); + + it('should return empty stringfor input empty', () => { + expect(ucwordsFilter('')).toBe(''); + }); + + it('should format a string uppercasing the first character of each word', () => { + expect(ucwordsFilter('abc def')).toBe('Abc Def'); + }); +}); diff --git a/front/core/filters/specs/zero-fill.spec.js b/front/core/filters/specs/zero-fill.spec.js new file mode 100644 index 000000000..9368e0722 --- /dev/null +++ b/front/core/filters/specs/zero-fill.spec.js @@ -0,0 +1,24 @@ +'use strict'; +describe('ZeroFill filter', () => { + beforeEach(ngModule('vnCore')); + let zeroFillFilter; + beforeEach(inject(_zeroFillFilter_ => { + zeroFillFilter = _zeroFillFilter_; + })); + + it('should return null for a input null', () => { + expect(zeroFillFilter(null, null)).toBeNull(); + }); + + it('should return a positive number pads a number with five zeros', () => { + expect(zeroFillFilter(1, 5)).toBe('00001'); + }); + + it('should return negative number pads a number with five zeros', () => { + expect(zeroFillFilter(-1, 5)).toBe('-00001'); + }); + + it('should return zero number with zero zeros', () => { + expect(zeroFillFilter(0, 1)).toBe('0'); + }); +}); From 7da7e6cfafc2a2a0f0681e25a4f7124022fc9304 Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 30 Apr 2020 08:13:25 +0200 Subject: [PATCH 22/25] test --- front/core/filters/specs/percentage.spec.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/front/core/filters/specs/percentage.spec.js b/front/core/filters/specs/percentage.spec.js index 8961dc1ee..f3ae0d7dc 100644 --- a/front/core/filters/specs/percentage.spec.js +++ b/front/core/filters/specs/percentage.spec.js @@ -1,6 +1,10 @@ 'use strict'; describe('Percentage filter', () => { beforeEach(ngModule('vnCore')); + let percentageFilter; + beforeEach(inject(_percentageFilter_ => { + percentageFilter = _percentageFilter_; + })); it('should return null for input null', () => { expect(percentageFilter(null, null)).toBeNull(); From 7e895749eb4c30e3eb3f6b2b43ebd936a9ae3c7f Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 30 Apr 2020 08:18:40 +0200 Subject: [PATCH 23/25] sin use strict --- front/core/filters/specs/dash-if-empty.spec.js | 5 +++-- front/core/filters/specs/percentage.spec.js | 5 +++-- front/core/filters/specs/phone.spec.js | 5 +++-- front/core/filters/specs/ucwords.spec.js | 5 +++-- front/core/filters/specs/zero-fill.spec.js | 5 +++-- 5 files changed, 15 insertions(+), 10 deletions(-) diff --git a/front/core/filters/specs/dash-if-empty.spec.js b/front/core/filters/specs/dash-if-empty.spec.js index 51e2222ca..552e97445 100644 --- a/front/core/filters/specs/dash-if-empty.spec.js +++ b/front/core/filters/specs/dash-if-empty.spec.js @@ -1,7 +1,8 @@ -'use strict'; describe('Dash-if-empty filter', () => { - beforeEach(ngModule('vnCore')); let dashIfEmptyFilter; + + beforeEach(ngModule('vnCore')); + beforeEach(inject(_dashIfEmptyFilter_ => { dashIfEmptyFilter = _dashIfEmptyFilter_; })); diff --git a/front/core/filters/specs/percentage.spec.js b/front/core/filters/specs/percentage.spec.js index f3ae0d7dc..0936c50ae 100644 --- a/front/core/filters/specs/percentage.spec.js +++ b/front/core/filters/specs/percentage.spec.js @@ -1,7 +1,8 @@ -'use strict'; describe('Percentage filter', () => { - beforeEach(ngModule('vnCore')); let percentageFilter; + + beforeEach(ngModule('vnCore')); + beforeEach(inject(_percentageFilter_ => { percentageFilter = _percentageFilter_; })); diff --git a/front/core/filters/specs/phone.spec.js b/front/core/filters/specs/phone.spec.js index fdff2556c..04de345e7 100644 --- a/front/core/filters/specs/phone.spec.js +++ b/front/core/filters/specs/phone.spec.js @@ -1,7 +1,8 @@ -'use strict'; describe('Phone filter', () => { - beforeEach(ngModule('vnCore')); let phoneFilter; + + beforeEach(ngModule('vnCore')); + beforeEach(inject(_phoneFilter_ => { phoneFilter = _phoneFilter_; })); diff --git a/front/core/filters/specs/ucwords.spec.js b/front/core/filters/specs/ucwords.spec.js index 640bcc0e4..0f13bd2a5 100644 --- a/front/core/filters/specs/ucwords.spec.js +++ b/front/core/filters/specs/ucwords.spec.js @@ -1,7 +1,8 @@ -'use strict'; describe('Ucwords filter', () => { - beforeEach(ngModule('vnCore')); let ucwordsFilter; + + beforeEach(ngModule('vnCore')); + beforeEach(inject(_ucwordsFilter_ => { ucwordsFilter = _ucwordsFilter_; })); diff --git a/front/core/filters/specs/zero-fill.spec.js b/front/core/filters/specs/zero-fill.spec.js index 9368e0722..97f04c655 100644 --- a/front/core/filters/specs/zero-fill.spec.js +++ b/front/core/filters/specs/zero-fill.spec.js @@ -1,7 +1,8 @@ -'use strict'; describe('ZeroFill filter', () => { - beforeEach(ngModule('vnCore')); let zeroFillFilter; + + beforeEach(ngModule('vnCore')); + beforeEach(inject(_zeroFillFilter_ => { zeroFillFilter = _zeroFillFilter_; })); From d960ac7d84d6bffe359324d418e19245de424401 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Sun, 3 May 2020 14:30:19 +0200 Subject: [PATCH 24/25] Removed max auth attempts --- README.md | 2 +- back/methods/chat/send.js | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ae3d01f1d..8960c8d00 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ ext install dbaeumer.vscode-eslint You will need to install globally the following items. ``` -# npm install -g jest gulp-cli nodemon +# sudo npm install -g jest gulp-cli nodemon ``` ## Linux Only Prerequisites diff --git a/back/methods/chat/send.js b/back/methods/chat/send.js index 53e5da7cc..6205bd03e 100644 --- a/back/methods/chat/send.js +++ b/back/methods/chat/send.js @@ -47,8 +47,7 @@ module.exports = Self => { 'alias': sender.nickname, 'text': message }).catch(async error => { - if (error.statusCode === 401 && !this.resendAttempted) { - this.resendAttempted = true; + if (error.statusCode === 401) { this.auth = null; return sendMessage(sender, channel, message); From 8453d25852f4916dfdec9b4d60b8fa32348eab74 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 6 May 2020 18:42:50 +0200 Subject: [PATCH 25/25] #2224item.diary provar directiva $anchorScroll --- .../02-sale_calculateComponent.sql | 16 +-- db/changes/10180-holyWeek/03-itemDiary.sql | 130 ++++++++++++++++++ e2e/helpers/selectors.js | 2 +- e2e/paths/05-ticket/11_diary.spec.js | 2 +- modules/claim/front/summary/index.html | 2 +- modules/claim/front/summary/index.js | 4 +- .../item/{getDiary.js => getBalance.js} | 8 +- .../back/methods/item/specs/getDiary.spec.js | 4 +- modules/item/back/models/item.js | 2 +- modules/item/front/diary/index.html | 12 +- modules/item/front/diary/index.js | 110 +++------------ modules/item/front/diary/index.spec.js | 65 --------- modules/item/front/routes.json | 2 +- modules/ticket/front/component/index.html | 2 +- modules/ticket/front/component/index.js | 8 +- modules/ticket/front/expedition/index.js | 16 +-- modules/ticket/front/request/index/index.html | 2 +- modules/ticket/front/request/index/index.js | 8 +- modules/ticket/front/sale-checked/index.html | 2 +- modules/ticket/front/sale-checked/index.js | 8 +- modules/ticket/front/sale-tracking/index.html | 2 +- modules/ticket/front/sale-tracking/index.js | 8 +- modules/ticket/front/sale/index.html | 2 +- modules/ticket/front/sale/index.js | 8 +- modules/ticket/front/summary/index.html | 4 +- modules/ticket/front/summary/index.js | 8 +- modules/ticket/front/volume/index.html | 2 +- modules/ticket/front/volume/index.js | 8 +- 28 files changed, 214 insertions(+), 233 deletions(-) create mode 100644 db/changes/10180-holyWeek/03-itemDiary.sql rename modules/item/back/methods/item/{getDiary.js => getBalance.js} (70%) diff --git a/db/changes/10180-holyWeek/02-sale_calculateComponent.sql b/db/changes/10180-holyWeek/02-sale_calculateComponent.sql index a0a5f8833..979608a35 100644 --- a/db/changes/10180-holyWeek/02-sale_calculateComponent.sql +++ b/db/changes/10180-holyWeek/02-sale_calculateComponent.sql @@ -15,8 +15,8 @@ proc: BEGIN DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; DECLARE vAddressFk INT; - DECLARE vTicket BIGINT; - DECLARE vItem BIGINT; + DECLARE vTicketFk BIGINT; + DECLARE vItemFk BIGINT; DECLARE vLanded DATE; DECLARE vIsEditable BOOLEAN; DECLARE vZoneFk INTEGER; @@ -31,8 +31,8 @@ proc: BEGIN t.agencyModeFk, t.landed INTO vIsEditable, - vTicket, - vItem, + vTicketFk, + vItemFk, vZoneFk, vWarehouseFk, vShipped, @@ -69,13 +69,13 @@ proc: BEGIN -- rellena la tabla buyUltimate con la ultima compra CALL buyUltimate (vWarehouseFk, vShipped); - DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + DELETE FROM tmp.buyUltimate WHERE itemFk != vItemFk; DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk, vZoneFk zoneFk + SELECT vWarehouseFk warehouseFk, NULL available, vItemFk itemFk, buyFk, vZoneFk zoneFk FROM tmp.buyUltimate - WHERE itemFk = vItem; + WHERE itemFk = vItemFk; CALL catalog_componentPrepare(); CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); @@ -92,7 +92,7 @@ proc: BEGIN CALL ticketComponentUpdateSale(vOption); INSERT INTO ticketLog (originFk, userFk, `action`, description) - VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + VALUES (vTicketFk, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); CALL catalog_componentPurge(); DROP TEMPORARY TABLE tmp.buyUltimate; diff --git a/db/changes/10180-holyWeek/03-itemDiary.sql b/db/changes/10180-holyWeek/03-itemDiary.sql new file mode 100644 index 000000000..d30597e14 --- /dev/null +++ b/db/changes/10180-holyWeek/03-itemDiary.sql @@ -0,0 +1,130 @@ +DROP procedure IF EXISTS `vn`.`item_getBalance`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `item_getBalance`(IN vItemId INT, IN vWarehouse INT) +BEGIN + DECLARE vDateInventory DATETIME; + DECLARE vCurdate DATE DEFAULT CURDATE(); + DECLARE vDayEnd DATETIME DEFAULT util.dayEnd(vCurdate); + + SELECT inventoried INTO vDateInventory FROM config; + SET @a = 0; + SET @currentLineFk = 0; + SET @shipped = ''; + + SELECT DATE(@shipped:= shipped) shipped, + alertLevel, + stateName, + origin, + reference, + clientFk, + name, + `in`, + `out`, + @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance, + @currentLineFk := IF (@shipped < CURDATE() + OR (@shipped = CURDATE() AND (isPicked OR alertLevel >= 2)), + lineFk,@currentLineFk) lastPreparedLineFk, + isTicket, + lineFk,isPicked + FROM + ( SELECT tr.landed as shipped, + b.quantity as `in`, + NULL as `out`, + al.alertLevel as alertLevel, + st.name AS stateName, + s.name as name, + e.ref as reference, + e.id as origin, + s.id as clientFk, + IF(al.alertLevel = 3, TRUE, FALSE) isPicked, + FALSE AS isTicket, + b.id lineFk, + NULL `order` + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + JOIN supplier s ON s.id = e.supplierFk + JOIN alertLevel al ON al.alertLevel = + CASE + WHEN tr.shipped < CURDATE() THEN 3 + WHEN tr.shipped = CURDATE() AND tr.isReceived = TRUE THEN 3 + ELSE 0 + END + JOIN state st ON st.code = al.code + WHERE tr.landed >= vDateInventory + AND vWarehouse = tr.warehouseInFk + AND b.itemFk = vItemId + AND e.isInventory = FALSE + AND e.isRaid = FALSE + UNION ALL + + SELECT tr.shipped, + NULL as `in`, + b.quantity as `out`, + al.alertLevel as alertLevel, + st.name AS stateName, + s.name as name, + e.ref as reference, + e.id as origin, + s.id as clientFk, + IF(al.alertLevel = 3, TRUE, FALSE) isPicked, + FALSE AS isTicket, + b.id, + NULL `order` + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + JOIN warehouse w ON w.id = tr.warehouseOutFk + JOIN supplier s ON s.id = e.supplierFk + JOIN alertLevel al ON al.alertLevel = + CASE + WHEN tr.shipped < CURDATE() THEN 3 + WHEN tr.shipped = CURDATE() AND tr.isReceived = TRUE THEN 3 + ELSE 0 + END + JOIN state st ON st.code = al.code + WHERE tr.shipped >= vDateInventory + AND vWarehouse =tr.warehouseOutFk + AND s.id <> 4 + AND b.itemFk = vItemId + AND e.isInventory = FALSE + AND w.isFeedStock = FALSE + AND e.isRaid = FALSE + UNION ALL + + SELECT DATE(t.shipped), + NULL as `in`, + s.quantity as `out`, + al.alertLevel as alertLevel, + st.name AS stateName, + t.nickname as name, + t.refFk as reference, + t.id as origin, + t.clientFk, + stk.id as isPicked, + TRUE as isTicket, + s.id, + st.`order` + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN ticketState ts ON ts.ticket = t.id + LEFT JOIN state st ON st.code = ts.code + JOIN client c ON c.id = t.clientFk + JOIN alertLevel al ON al.alertLevel = + CASE + WHEN t.shipped < curdate() THEN 3 + WHEN t.shipped > util.dayEnd(curdate()) THEN 0 + ELSE IFNULL(ts.alertLevel, 0) + END + LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED' + LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = stPrep.id + WHERE t.shipped >= vDateInventory + AND s.itemFk = vItemId + AND vWarehouse =t.warehouseFk + ORDER BY shipped, alertLevel DESC, isTicket, `order` DESC, isPicked DESC, `in` DESC, `out` DESC + ) AS itemDiary; + +END$$ +delimiter ; \ No newline at end of file diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 551573836..6ec1d8ebe 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -354,7 +354,7 @@ export default { firstSaleItemId: 'vn-ticket-summary [name="sales"] vn-table vn-tbody > :nth-child(1) > vn-td:nth-child(2) > span', firstSaleDescriptorImage: '.vn-popover.shown vn-item-descriptor img', itemDescriptorPopover: '.vn-popover.shown vn-item-descriptor', - itemDescriptorPopoverItemDiaryButton: 'vn-item-descriptor a[href="#!/item/2/diary?warehouseFk=5&ticketFk=20"]', + itemDescriptorPopoverItemDiaryButton: 'vn-item-descriptor a[href="#!/item/2/diary?warehouseFk=5&lineFk=16"]', popoverDiaryButton: '.vn-popover.shown vn-item-descriptor vn-icon[icon="icon-transaction"]', firstSaleQuantity: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(3)', firstSaleDiscount: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(6)', diff --git a/e2e/paths/05-ticket/11_diary.spec.js b/e2e/paths/05-ticket/11_diary.spec.js index a75e1ae24..e4c63855a 100644 --- a/e2e/paths/05-ticket/11_diary.spec.js +++ b/e2e/paths/05-ticket/11_diary.spec.js @@ -1,7 +1,7 @@ import selectors from '../../helpers/selectors.js'; import getBrowser from '../../helpers/puppeteer'; -// #2221 Local MySQL8 crashes when rest method Items/getDiary is called +// #2221 Local MySQL8 crashes when rest method Items/getBalance is called xdescribe('Ticket diary path', () => { let page; diff --git a/modules/claim/front/summary/index.html b/modules/claim/front/summary/index.html index 6f639c709..44a093336 100644 --- a/modules/claim/front/summary/index.html +++ b/modules/claim/front/summary/index.html @@ -61,7 +61,7 @@ {{::saleClaimed.sale.itemFk | zeroFill:6}} diff --git a/modules/claim/front/summary/index.js b/modules/claim/front/summary/index.js index 094aa49fe..a9bde7289 100644 --- a/modules/claim/front/summary/index.js +++ b/modules/claim/front/summary/index.js @@ -33,8 +33,8 @@ class Controller extends Section { }); } - showItemDescriptor(event, itemFk) { - this.$.itemDescriptor.itemFk = itemFk; + showItemDescriptor(event, sale) { + this.$.itemDescriptor.itemFk = sale.itemFk; this.$.itemDescriptor.parent = event.target; this.$.itemDescriptor.show(); } diff --git a/modules/item/back/methods/item/getDiary.js b/modules/item/back/methods/item/getBalance.js similarity index 70% rename from modules/item/back/methods/item/getDiary.js rename to modules/item/back/methods/item/getBalance.js index 5d8259867..26fc2a7dc 100644 --- a/modules/item/back/methods/item/getDiary.js +++ b/modules/item/back/methods/item/getBalance.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('getDiary', { + Self.remoteMethod('getBalance', { description: 'Returns the ', accessType: 'READ', accepts: [{ @@ -14,14 +14,14 @@ module.exports = Self => { root: true }, http: { - path: `/getDiary`, + path: `/getBalance`, verb: 'GET' } }); - Self.getDiary = async filter => { + Self.getBalance = async filter => { let where = filter.where; - let [diary] = await Self.rawSql(`CALL vn.itemDiary(?, ?)`, [where.itemFk, where.warehouseFk]); + let [diary] = await Self.rawSql(`CALL vn.item_getBalance(?, ?)`, [where.itemFk, where.warehouseFk]); return diary; }; }; diff --git a/modules/item/back/methods/item/specs/getDiary.spec.js b/modules/item/back/methods/item/specs/getDiary.spec.js index d47ac1d7d..cf9ed9320 100644 --- a/modules/item/back/methods/item/specs/getDiary.spec.js +++ b/modules/item/back/methods/item/specs/getDiary.spec.js @@ -1,9 +1,9 @@ const app = require('vn-loopback/server/server'); -describe('item getDiary()', () => { +describe('item getBalance()', () => { it('should check the property balance of the 4 resultant entries', async() => { let params = {where: {itemFk: 1, warehouseFk: 2}}; - let result = await app.models.Item.getDiary(params); + let result = await app.models.Item.getBalance(params); expect(result.length).toBe(4); expect(result[0].balance).toBe(-100); diff --git a/modules/item/back/models/item.js b/modules/item/back/models/item.js index 01061ce99..d273404ea 100644 --- a/modules/item/back/models/item.js +++ b/modules/item/back/models/item.js @@ -4,7 +4,7 @@ module.exports = Self => { require('../methods/item/filter')(Self); require('../methods/item/clone')(Self); require('../methods/item/updateTaxes')(Self); - require('../methods/item/getDiary')(Self); + require('../methods/item/getBalance')(Self); require('../methods/item/getLastEntries')(Self); require('../methods/item/getSummary')(Self); require('../methods/item/getCard')(Self); diff --git a/modules/item/front/diary/index.html b/modules/item/front/diary/index.html index f3c9ff63a..40d398e7a 100644 --- a/modules/item/front/diary/index.html +++ b/modules/item/front/diary/index.html @@ -1,6 +1,6 @@ @@ -39,11 +39,12 @@ 'balanceNegative': sale.balance < 0}" ng-repeat="sale in sales" vn-repeat-last - on-last="$ctrl.scrollToLine()"> + on-last="$ctrl.scrollToLine(sale.lastPreparedLineFk)" + ng-attr-id="vnItemDiary-{{::sale.lineFk}}"> - {{::sale.date | date:'dd/MM/yyyy' }} + ng-class="::{warning: $ctrl.today == sale.shipped}"> + {{::sale.shipped | date:'dd/MM/yyyy' }} @@ -66,7 +67,8 @@ {{::sale.in | dashIfEmpty}} {{::sale.out | dashIfEmpty}} - + {{::sale.balance | dashIfEmpty}} diff --git a/modules/item/front/diary/index.js b/modules/item/front/diary/index.js index e77ad1c2c..55b63a60e 100644 --- a/modules/item/front/diary/index.js +++ b/modules/item/front/diary/index.js @@ -3,6 +3,15 @@ import Section from 'salix/components/section'; import './style.scss'; class Controller extends Section { + constructor($element, $scope, $anchorScroll, $location) { + super($element, $scope); + this.$anchorScroll = $anchorScroll; + this.$location = $location; + let today = new Date(); + today.setHours(0, 0, 0, 0); + this.today = today.toJSON(); + } + get item() { return this._item; } @@ -20,8 +29,8 @@ class Controller extends Section { else if (value) this.warehouseFk = value.itemType.warehouseFk; - if (this.$params.ticketFk) - this.ticketFk = this.$params.ticketFk; + if (this.$params.lineFk) + this.lineFk = this.$params.lineFk; }); } @@ -42,96 +51,11 @@ class Controller extends Section { return this._warehouseFk; } - get freeLineIndex() { - let lines = this.$.model.data; - let minDate = new Date(); - minDate.setHours(0, 0, 0, 0); - - let maxDate = new Date(); - maxDate.setHours(23, 59, 59, 59); - - for (let i = 0; i < lines.length; i++) { - const dated = new Date(lines[i].date); - - let isForFuture = dated > maxDate; - let isForToday = (dated >= minDate && dated <= maxDate); - if (isForFuture || isForToday) - return i; - } - } - - get onPreparationLineIndex() { - let lines = this.$.model.data; - for (let i = this.freeLineIndex; i >= 0; i--) { - let line = lines[i]; - - let currentDate = new Date(); - currentDate.setHours(0, 0, 0, 0); - - let isPastDate = new Date(lines[i].date) < currentDate; - let isPicked = line.alertLevel == 1 && line.isPicked; - - if ((isPicked) || line.alertLevel > 1 || isPastDate) - return i + 1; - } - } - - get givenTicketIndex() { - let lines = this.$.model.data; - - for (let i = lines.length - 1; i > 0; i--) { - let line = lines[i]; - - if (line.origin == this.ticketFk) - return i; - } - } - - scrollToLine() { - let body = this.$window.document.body; - let selectedTicketLineIndex = this.givenTicketIndex; - let lineIndex = this.onPreparationLineIndex; - - let lines = body.querySelector('vn-tbody').children; - - if (lineIndex == undefined || !lines.length) return; - - let onPreparationLine = lines[lineIndex]; - - let balance = onPreparationLine.querySelector('.balanceSpan'); - balance.classList.add('message'); - balance.title = this.$translate.instant('Visible quantity'); - - let headerOffset = body.querySelector('vn-topbar').getBoundingClientRect(); - let headerHeight = headerOffset.height; - - let offsetTop; - if (this.ticketFk) { - let selectedTicketLine = lines[selectedTicketLineIndex]; - let id = selectedTicketLine.querySelector('[name=origin]'); - id.classList.add('message'); - offsetTop = selectedTicketLine.offsetTop - headerHeight; - } else - offsetTop = onPreparationLine.offsetTop - headerHeight; - - this.$window.scrollTo(0, offsetTop); - this.ticketFk = null; - } - - /** - * Compares a date with the current one - * @param {Object} date - Date to compare - * @return {Boolean} - Returns true if the two dates equals - */ - isToday(date) { - let today = new Date(); - today.setHours(0, 0, 0, 0); - - let comparedDate = new Date(date); - comparedDate.setHours(0, 0, 0, 0); - - if (!(today - comparedDate)) - return true; + scrollToLine(lineFk) { + const hashFk = this.lineFk || lineFk; + const hash = `vnItemDiary-${hashFk}`; + this.$location.hash(hash); + this.$anchorScroll(); } showDescriptor(event, sale) { @@ -159,6 +83,8 @@ class Controller extends Section { } } +Controller.$inject = ['$element', '$scope', '$anchorScroll', '$location']; + ngModule.component('vnItemDiary', { template: require('./index.html'), controller: Controller, diff --git a/modules/item/front/diary/index.spec.js b/modules/item/front/diary/index.spec.js index 94458a569..ccf7ac1a1 100644 --- a/modules/item/front/diary/index.spec.js +++ b/modules/item/front/diary/index.spec.js @@ -16,56 +16,6 @@ describe('Item', () => { controller.$params = {id: 1}; })); - describe('isToday()', () => { - it(`should call isToday() an return true if an specified date is the current date`, () => { - let date = new Date(); - - let result = controller.isToday(date); - - expect(result).toBeTruthy(); - }); - - it(`should call isToday() an return false if an specified date is the current date`, () => { - let date = '2018-07-03'; - - let result = controller.isToday(date); - - expect(result).toBeFalsy(); - }); - }); - - describe('freeLineIndex()', () => { - it(`should call freeLineIndex() and return an index from line with alertLevel 0 and current date`, () => { - let currentDate = new Date(); - currentDate.setDate(currentDate.getDate() + 1); - - controller.$.model = {data: [ - {name: 'My item 1', alertLevel: 3, date: '2018-05-02'}, - {name: 'My item 2', alertLevel: 1, date: '2018-05-03'}, - {name: 'My item 3', alertLevel: 0, date: currentDate}] - }; - let result = controller.freeLineIndex; - - expect(result).toEqual(2); - }); - }); - - describe('onPreparationLineIndex()', () => { - it(`should call onPreparationLineIndex() and return an index from line with alertLevel 1 and isPicked true`, () => { - let currentDate = new Date(); - currentDate.setDate(currentDate.getDate() + 1); - controller.$.model = {data: [ - {name: 'My item 1', alertLevel: 3, isPicked: true, date: currentDate}, - {name: 'My item 3', alertLevel: 1, isPicked: true, date: currentDate}, - {name: 'My item 4', alertLevel: 1, isPicked: false, date: currentDate}, - {name: 'My item 5', alertLevel: 0, isPicked: false, date: currentDate}] - }; - let result = controller.onPreparationLineIndex; - - expect(result).toEqual(1); - }); - }); - describe('set item()', () => { it('should set warehouseFk property based on itemType warehouseFk', () => { jest.spyOn(controller.$, '$applyAsync'); @@ -90,21 +40,6 @@ describe('Item', () => { expect(controller.item.id).toEqual(1); }); }); - - describe('givenTicketIndex() setter', () => { - it(`should return the index position of the line of a given ticket fk`, () => { - controller.$.model = {data: [ - {name: 'My item 1', origin: 1, alertLevel: 3, isPicked: true, date: '2018-05-02'}, - {name: 'My item 3', origin: 2, alertLevel: 1, isPicked: true, date: '2018-05-03'}, - {name: 'My item 4', origin: 3, alertLevel: 1, isPicked: false, date: '2018-05-03'}] - }; - controller.ticketFk = 2; - - let index = controller.givenTicketIndex; - - expect(controller.$.model.data[index].origin).toEqual(2); - }); - }); }); }); diff --git a/modules/item/front/routes.json b/modules/item/front/routes.json index a3cf0bee6..2aab4301e 100644 --- a/modules/item/front/routes.json +++ b/modules/item/front/routes.json @@ -107,7 +107,7 @@ "item": "$ctrl.item" } }, { - "url" : "/diary?warehouseFk&ticketFk", + "url" : "/diary?warehouseFk&lineFk", "state": "item.card.diary", "component": "vn-item-diary", "description": "Diary", diff --git a/modules/ticket/front/component/index.html b/modules/ticket/front/component/index.html index e555eb8d7..a39233563 100644 --- a/modules/ticket/front/component/index.html +++ b/modules/ticket/front/component/index.html @@ -27,7 +27,7 @@ {{sale.itemFk | zeroFill:6}} diff --git a/modules/ticket/front/component/index.js b/modules/ticket/front/component/index.js index d0b6ed880..40054571e 100644 --- a/modules/ticket/front/component/index.js +++ b/modules/ticket/front/component/index.js @@ -47,19 +47,19 @@ class Controller extends Section { return sum; } - showDescriptor(event, itemFk) { + showDescriptor(event, sale) { this.quicklinks = { btnThree: { icon: 'icon-transaction', state: `item.card.diary({ - id: ${itemFk}, + id: ${sale.itemFk}, warehouseFk: ${this.ticket.warehouseFk}, - ticketFk: ${this.ticket.id} + lineFk: ${sale.id} })`, tooltip: 'Item diary' } }; - this.$.descriptor.itemFk = itemFk; + this.$.descriptor.itemFk = sale.itemFk; this.$.descriptor.parent = event.target; this.$.descriptor.show(); } diff --git a/modules/ticket/front/expedition/index.js b/modules/ticket/front/expedition/index.js index 1079e0b21..28193cd3b 100644 --- a/modules/ticket/front/expedition/index.js +++ b/modules/ticket/front/expedition/index.js @@ -15,20 +15,8 @@ class Controller extends Section { } } - showItemDescriptor(event, itemFk) { - if (!itemFk) return; - this.quicklinks = { - btnThree: { - icon: 'icon-transaction', - state: `item.card.diary({ - id: ${itemFk}, - warehouseFk: ${this.ticket.warehouseFk}, - ticketFk: ${this.ticket.id} - })`, - tooltip: 'Item diary', - }, - }; - this.$.itemDescriptor.itemFk = itemFk; + showItemDescriptor(event, sale) { + this.$.itemDescriptor.itemFk = sale.itemFk; this.$.itemDescriptor.parent = event.target; this.$.itemDescriptor.show(); } diff --git a/modules/ticket/front/request/index/index.html b/modules/ticket/front/request/index/index.html index 0acb661e3..eeb111a8f 100644 --- a/modules/ticket/front/request/index/index.html +++ b/modules/ticket/front/request/index/index.html @@ -73,7 +73,7 @@ {{::request.saleFk | zeroFill:6}} diff --git a/modules/ticket/front/request/index/index.js b/modules/ticket/front/request/index/index.js index c2e6dc123..d1a2b3d61 100644 --- a/modules/ticket/front/request/index/index.js +++ b/modules/ticket/front/request/index/index.js @@ -44,18 +44,18 @@ class Controller extends Section { }); } - showItemDescriptor(event, itemFk) { + showItemDescriptor(event, sale) { this.quicklinks = { btnThree: { icon: 'icon-transaction', state: `item.card.diary({ - id: ${itemFk}, - ticketFk: ${this.$params.id} + id: ${sale.itemFk}, + lineFk: ${sale.id} })`, tooltip: 'Item diary' } }; - this.$.itemDescriptor.itemFk = itemFk; + this.$.itemDescriptor.itemFk = sale.itemFk; this.$.itemDescriptor.parent = event.target; this.$.itemDescriptor.show(); } diff --git a/modules/ticket/front/sale-checked/index.html b/modules/ticket/front/sale-checked/index.html index a2afd3b8f..e96d93d05 100644 --- a/modules/ticket/front/sale-checked/index.html +++ b/modules/ticket/front/sale-checked/index.html @@ -29,7 +29,7 @@ {{::sale.itemFk | zeroFill:6}} diff --git a/modules/ticket/front/sale-checked/index.js b/modules/ticket/front/sale-checked/index.js index 1fd9b662b..ad98bfb12 100644 --- a/modules/ticket/front/sale-checked/index.js +++ b/modules/ticket/front/sale-checked/index.js @@ -17,19 +17,19 @@ class Controller extends Section { }; } - showDescriptor(event, itemFk) { + showDescriptor(event, sale) { this.quicklinks = { btnThree: { icon: 'icon-transaction', state: `item.card.diary({ - id: ${itemFk}, + id: ${sale.itemFk}, warehouseFk: ${this.ticket.warehouseFk}, - ticketFk: ${this.ticket.id} + lineFk: ${sale.id} })`, tooltip: 'Item diary' } }; - this.$.descriptor.itemFk = itemFk; + this.$.descriptor.itemFk = sale.itemFk; this.$.descriptor.parent = event.target; this.$.descriptor.show(); } diff --git a/modules/ticket/front/sale-tracking/index.html b/modules/ticket/front/sale-tracking/index.html index b365ef1ca..c5ef66d77 100644 --- a/modules/ticket/front/sale-tracking/index.html +++ b/modules/ticket/front/sale-tracking/index.html @@ -34,7 +34,7 @@ {{sale.itemFk | zeroFill:6}} diff --git a/modules/ticket/front/sale-tracking/index.js b/modules/ticket/front/sale-tracking/index.js index 8dca9c026..6ad929636 100644 --- a/modules/ticket/front/sale-tracking/index.js +++ b/modules/ticket/front/sale-tracking/index.js @@ -2,19 +2,19 @@ import ngModule from '../module'; import Section from 'salix/components/section'; class Controller extends Section { - showItemDescriptor(event, itemFk) { + showItemDescriptor(event, sale) { this.quicklinks = { btnThree: { icon: 'icon-transaction', state: `item.card.diary({ - id: ${itemFk}, + id: ${sale.itemFk}, warehouseFk: ${this.ticket.warehouseFk}, - ticketFk: ${this.ticket.id} + lineFk: ${sale.id} })`, tooltip: 'Item diary', }, }; - this.$.itemDescriptor.itemFk = itemFk; + this.$.itemDescriptor.itemFk = sale.itemFk; this.$.itemDescriptor.parent = event.target; this.$.itemDescriptor.show(); } diff --git a/modules/ticket/front/sale/index.html b/modules/ticket/front/sale/index.html index e120ad942..a7315e79c 100644 --- a/modules/ticket/front/sale/index.html +++ b/modules/ticket/front/sale/index.html @@ -106,7 +106,7 @@ + ng-click="$ctrl.showDescriptor($event, sale)"> {{sale.itemFk}} {{sale.itemFk | zeroFill:6}} @@ -208,7 +208,7 @@ {{request.sale.itemFk | zeroFill:6}} diff --git a/modules/ticket/front/summary/index.js b/modules/ticket/front/summary/index.js index 7e892b265..e240cdfc0 100644 --- a/modules/ticket/front/summary/index.js +++ b/modules/ticket/front/summary/index.js @@ -44,19 +44,19 @@ class Controller extends Section { this.$.routeDescriptor.show(); } - showDescriptor(event, itemFk) { + showDescriptor(event, sale) { this.quicklinks = { btnThree: { icon: 'icon-transaction', state: `item.card.diary({ - id: ${itemFk}, + id: ${sale.itemFk}, warehouseFk: ${this.ticket.warehouseFk}, - ticketFk: ${this.ticket.id} + lineFk: ${sale.id} })`, tooltip: 'Item diary' } }; - this.$.descriptor.itemFk = itemFk; + this.$.descriptor.itemFk = sale.itemFk; this.$.descriptor.parent = event.target; this.$.descriptor.show(); } diff --git a/modules/ticket/front/volume/index.html b/modules/ticket/front/volume/index.html index 977f76513..0ecd6ef91 100644 --- a/modules/ticket/front/volume/index.html +++ b/modules/ticket/front/volume/index.html @@ -37,7 +37,7 @@ {{sale.itemFk | zeroFill:6}} diff --git a/modules/ticket/front/volume/index.js b/modules/ticket/front/volume/index.js index bf616cb24..3bdb9df9f 100644 --- a/modules/ticket/front/volume/index.js +++ b/modules/ticket/front/volume/index.js @@ -44,19 +44,19 @@ class Controller extends Section { }); } - showDescriptor(event, itemFk) { + showDescriptor(event, sale) { this.quicklinks = { btnThree: { icon: 'icon-transaction', state: `item.card.diary({ - id: ${itemFk}, + id: ${sale.itemFk}, warehouseFk: ${this.ticket.warehouseFk}, - ticketFk: ${this.ticket.id} + lineFk: ${sale.id} })`, tooltip: 'Item diary' } }; - this.$.descriptor.itemFk = itemFk; + this.$.descriptor.itemFk = sale.itemFk; this.$.descriptor.parent = event.target; this.$.descriptor.show(); }