diff --git a/CHANGELOG.md b/CHANGELOG.md index 4572b137a..f59a3d4c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,6 +102,7 @@ - feat: refs #7438 Added volume to item_valuateInventory by:guillermo - feat: refs #7438 Requested changes and little changes by:guillermo - refs #6281 feat:buyFk in itemShelving by:sergiodt +- feat: refs #6449 item ID is displayed in the sale line by:jorgep ### Changed 馃摝 diff --git a/back/methods/collection/spec/getSales.spec.js b/back/methods/collection/spec/getSales.spec.js index e6205cc79..520657ec1 100644 --- a/back/methods/collection/spec/getSales.spec.js +++ b/back/methods/collection/spec/getSales.spec.js @@ -4,15 +4,7 @@ describe('collection getSales()', () => { const collectionOrTicketFk = 999999; const print = true; const source = 'CHECKER'; - - beforeAll(() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'}, - } - }; - }); + const ctx = beforeAll.getCtx(); it('should return a collection with tickets, placements and barcodes settled correctly', async() => { const tx = await models.Collection.beginTransaction({}); diff --git a/back/methods/collection/spec/getTickets.spec.js b/back/methods/collection/spec/getTickets.spec.js index 969800839..0e006706d 100644 --- a/back/methods/collection/spec/getTickets.spec.js +++ b/back/methods/collection/spec/getTickets.spec.js @@ -1,15 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('collection getTickets()', () => { - let ctx; - beforeAll(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - } - }; - }); + const ctx = beforeAll.getCtx(); it('should get tickets, sales and barcodes from collection', async() => { const tx = await models.Collection.beginTransaction({}); diff --git a/back/methods/collection/spec/setSaleQuantity.spec.js b/back/methods/collection/spec/setSaleQuantity.spec.js index b563f5b19..00ddae0fe 100644 --- a/back/methods/collection/spec/setSaleQuantity.spec.js +++ b/back/methods/collection/spec/setSaleQuantity.spec.js @@ -1,20 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('setSaleQuantity()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should change quantity sale', async() => { const tx = await models.Ticket.beginTransaction({}); diff --git a/back/methods/starred-module/specs/getStarredModules.spec.js b/back/methods/starred-module/specs/getStarredModules.spec.js index bf9bd1d73..afe1dd9c2 100644 --- a/back/methods/starred-module/specs/getStarredModules.spec.js +++ b/back/methods/starred-module/specs/getStarredModules.spec.js @@ -1,22 +1,7 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('getStarredModules()', () => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - const ctx = {req: activeCtx}; - - beforeEach(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.getCtx(); it(`should return the starred modules for a given user`, async() => { const newStarred = await models.StarredModule.create({workerFk: 9, moduleFk: 'customer', position: 1}); diff --git a/back/methods/starred-module/specs/setPosition.spec.js b/back/methods/starred-module/specs/setPosition.spec.js index a428fcf22..63addeffc 100644 --- a/back/methods/starred-module/specs/setPosition.spec.js +++ b/back/methods/starred-module/specs/setPosition.spec.js @@ -1,24 +1,8 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('setPosition()', () => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - const ctx = { - req: activeCtx - }; - - beforeEach(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.getCtx(); + beforeAll.mockLoopBackContext(); it('should increase the orders module position by replacing it with clients and vice versa', async() => { const tx = await models.StarredModule.beginTransaction({}); diff --git a/back/methods/starred-module/specs/toggleStarredModule.spec.js b/back/methods/starred-module/specs/toggleStarredModule.spec.js index 848c1475a..d506abc33 100644 --- a/back/methods/starred-module/specs/toggleStarredModule.spec.js +++ b/back/methods/starred-module/specs/toggleStarredModule.spec.js @@ -1,24 +1,7 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('toggleStarredModule()', () => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - const ctx = { - req: activeCtx - }; - - beforeEach(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.getCtx(); it('should create a new starred module and then remove it by calling the method again with same args', async() => { const starredModule = await models.StarredModule.toggleStarredModule(ctx, 'order'); @@ -26,7 +9,7 @@ describe('toggleStarredModule()', () => { expect(starredModules.length).toEqual(1); expect(starredModule.moduleFk).toEqual('order'); - expect(starredModule.workerFk).toEqual(activeCtx.accessToken.userId); + expect(starredModule.workerFk).toEqual(ctx.req.accessToken.userId); expect(starredModule.position).toEqual(starredModules.length); await models.StarredModule.toggleStarredModule(ctx, 'order'); diff --git a/back/methods/user-config/specs/getUserConfig.spec.js b/back/methods/user-config/specs/getUserConfig.spec.js index 8b510a706..bbfb98ef7 100644 --- a/back/methods/user-config/specs/getUserConfig.spec.js +++ b/back/methods/user-config/specs/getUserConfig.spec.js @@ -1,12 +1,12 @@ const models = require('vn-loopback/server/server').models; describe('userConfig getUserConfig()', () => { + const ctx = beforeAll.getCtx(); it(`should return the configuration data of a given user`, async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { - const ctx = {req: {accessToken: {userId: 9}}}; const result = await models.UserConfig.getUserConfig(ctx, options); expect(result.warehouseFk).toEqual(1); diff --git a/back/models/specs/mailAliasAccount.spec.js b/back/models/specs/mailAliasAccount.spec.js index 8f0278a50..0f4cbdbb1 100644 --- a/back/models/specs/mailAliasAccount.spec.js +++ b/back/models/specs/mailAliasAccount.spec.js @@ -1,12 +1,13 @@ const models = require('vn-loopback/server/server').models; describe('loopback model MailAliasAccount', () => { + const ctx = beforeAll.getCtx(); it('should add a mail Alias', async() => { const tx = await models.MailAliasAccount.beginTransaction({}); let error; try { - const options = {transaction: tx, accessToken: {userId: 9}}; + const options = {transaction: tx, ctx}; await models.MailAliasAccount.create({mailAlias: 2, account: 5}, options); await tx.rollback(); @@ -23,7 +24,7 @@ describe('loopback model MailAliasAccount', () => { let error; try { - const options = {transaction: tx, accessToken: {userId: 9}}; + const options = {transaction: tx, ctx}; await models.MailAliasAccount.create({mailAlias: 3, account: 5}, options); await tx.rollback(); diff --git a/back/models/warehouse.json b/back/models/warehouse.json index 756a538c0..54006130b 100644 --- a/back/models/warehouse.json +++ b/back/models/warehouse.json @@ -1,59 +1,59 @@ -{ - "name": "Warehouse", - "description": "Warehouses from where orders are sent", - "base": "VnModel", - "options": { - "mysql": { - "table": "warehouse" - } - }, - "properties": { - "id": { - "id": true, - "type": "number", - "forceId": false - }, - "name": { - "type": "string" - }, - "code": { - "type": "string" - }, - "isInventory": { - "type": "number" - }, - "isManaged": { - "type": "boolean" - }, - "countryFk": { - "type": "number" - } - }, - "relations": { - "country": { - "type": "belongsTo", - "model": "Country", - "foreignKey": "countryFk" - }, - "address": { - "type": "belongsTo", - "model": "Address", - "foreignKey": "addressFk" - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ], - "scope": { - "where": { - "isForTicket": { - "neq": 0 - } - } - } -} \ No newline at end of file +{ + "name": "Warehouse", + "description": "Warehouses from where orders are sent", + "base": "VnModel", + "options": { + "mysql": { + "table": "warehouse" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "forceId": false + }, + "name": { + "type": "string" + }, + "code": { + "type": "string" + }, + "isInventory": { + "type": "number" + }, + "isManaged": { + "type": "boolean" + }, + "countryFk": { + "type": "number" + } + }, + "relations": { + "country": { + "type": "belongsTo", + "model": "Country", + "foreignKey": "countryFk" + }, + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ], + "scope": { + "where": { + "isForTicket": { + "neq": 0 + } + } + } +} diff --git a/back/tests-helper.js b/back/tests-helper.js index 6d465bc2a..96f75f064 100644 --- a/back/tests-helper.js +++ b/back/tests-helper.js @@ -10,7 +10,6 @@ async function init() { host: process.env.DB_HOST, port: process.env.DB_PORT }); - const bootOptions = {dataSources}; await new Promise((resolve, reject) => { app.boot(bootOptions, @@ -33,3 +32,4 @@ module.exports = { if (require.main === module) init(); + diff --git a/back/tests.js b/back/tests.js index 50698eb92..2527367c2 100644 --- a/back/tests.js +++ b/back/tests.js @@ -84,7 +84,7 @@ async function test() { 'loopback/**/*[sS]pec.js', 'modules/*/back/**/*.[sS]pec.js' ], - helpers: [] + helpers: [`back/vn-jasmine.js`], }; if (PARALLEL) { @@ -114,7 +114,6 @@ async function test() { if (opts.ci) runner.jasmine.DEFAULT_TIMEOUT_INTERVAL = SPEC_TIMEOUT; - // runner.loadConfigFile('back/jasmine.json'); runner.loadConfig(config); process.env.SPEC_IS_RUNNING = true; await runner.execute(); diff --git a/back/vn-jasmine.js b/back/vn-jasmine.js new file mode 100644 index 000000000..2b981c6d9 --- /dev/null +++ b/back/vn-jasmine.js @@ -0,0 +1,48 @@ + +const LoopBackContext = require('loopback-context'); +const getAccessToken = (userId = 9) => { + return {accessToken: {userId}}; +}; +const DEFAULT_HEADERS = {headers: {origin: 'http://localhost'}}; +const default_before_all = userId => { + return { + req: { + ...getAccessToken(userId), + ...DEFAULT_HEADERS, + ...{__: value => value} + + }, + args: {} + }; +}; +const default_loopback_ctx = userId => { + return { + ...getAccessToken(userId), + ...default_before_all(userId), + http: { + ...default_before_all(userId) + }, + args: {} + }; +}; + +function vnBeforeAll() { + Object.assign(beforeAll, {getCtx: default_before_all, mockLoopBackContext}); +} + +const mockLoopBackContext = userId => { + const activeCtx = default_loopback_ctx(userId); + beforeAll(() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + }); + return activeCtx; +}; +module.exports = { + mockLoopBackContext +}; + +(function init() { + vnBeforeAll(); +})(); diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index 562ea02d8..84ce0d940 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -314,5 +314,4 @@ INSERT INTO mysql.roles_mapping (`User`, `Host`, `Role`, `Admin_option`) SELECT SUBSTR(`User`, @prefixLen + 1), `Host`, `Role`, `Admin_option` FROM mysql.roles_mapping WHERE `User` LIKE @prefixedLike AND `Host` = @genRoleHost; - FLUSH PRIVILEGES; diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 97e5f5f47..db0fab77f 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -115,10 +115,13 @@ INSERT INTO `hedera`.`tpvConfig`(`id`, `currency`, `terminal`, `transactionType` VALUES (1, 978, 1, 0, 2000, 9, 0); +INSERT INTO hedera.orderConfig (`id`, `employeeFk`, `defaultAgencyFk`, `guestMethod`, `guestAgencyFk`, `reserveTime`, `defaultCompanyFk`) + VALUES (1, 1, 2, 'PICKUP', 1, '00:20:00', 442); + INSERT INTO `account`.`user`(`id`,`name`,`nickname`, `password`,`role`,`active`,`email`,`lang`, `image`) VALUES (1101, 'brucewayne', 'Bruce Wayne', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'BruceWayne@mydomain.com', 'es','1101'), - (1102, 'petterparker', 'Petter Parker', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'PetterParker@mydomain.com', 'en','1102'), + (1102, 'petterparker', 'Petter Parker', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 131, 1, 'PetterParker@mydomain.com', 'en','1102'), (1103, 'clarkkent', 'Clark Kent', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'ClarkKent@mydomain.com', 'fr','1103'), (1104, 'tonystark', 'Tony Stark', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'TonyStark@mydomain.com', 'es','1104'), (1105, 'maxeisenhardt', 'Max Eisenhardt', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt','1105'), @@ -301,6 +304,17 @@ UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 8; UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 4 WHERE `id` = 23; UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 10; +UPDATE `vn`.`agencyMode` SET `description` = 'inhouse pickup' WHERE `id` = 1; +UPDATE `vn`.`agencyMode` SET `description` = 'Super-Man delivery' WHERE `id` = 2; +UPDATE `vn`.`agencyMode` SET `description` = 'Teleportation device' WHERE `id` = 3; +UPDATE `vn`.`agencyMode` SET `description` = 'Entanglement' WHERE `id` = 4; +UPDATE `vn`.`agencyMode` SET `description` = 'Quantum break device' WHERE `id` = 5; +UPDATE `vn`.`agencyMode` SET `description` = 'Walking' WHERE `id` = 6; +UPDATE `vn`.`agencyMode` SET `description` = 'Gotham247' WHERE `id` = 7; +UPDATE `vn`.`agencyMode` SET `description` = 'Gotham247Expensive' WHERE `id` = 8; +UPDATE `vn`.`agencyMode` SET `description` = 'Other agency' WHERE `id` = 10; +UPDATE `vn`.`agencyMode` SET `description` = 'Refund' WHERE `id` = 23; + UPDATE `vn`.`agencyMode` SET `web` = 1, `reportMail` = 'no-reply@gothamcity.com'; UPDATE `vn`.`agencyMode` SET `code` = 'refund' WHERE `id` = 23; @@ -528,7 +542,8 @@ INSERT INTO `vn`.`observationType`(`id`,`description`, `code`) (5, 'Administrative', 'administrative'), (6, 'Weight', 'weight'), (7, 'InvoiceOut', 'invoiceOut'), - (8, 'DropOff', 'dropOff'); + (8, 'DropOff', 'dropOff'), + (9, 'Sustituci贸n', 'substitution'); INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`) VALUES @@ -978,6 +993,14 @@ INSERT INTO `vn`.`priceFixed`(`id`, `itemFk`, `rate0`, `rate1`, `rate2`, `rate3` (2, 3, 10, 10, 10, 10, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), 0, 1, util.VN_CURDATE()), (3, 13, 8.5, 10, 7.5, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), 1, 2, util.VN_CURDATE()); +INSERT INTO `vn`.`itemMinimumQuantity`(`itemFk`, `quantity`, `started`, `ended`, `warehouseFk`) + VALUES + (1, 5, util.VN_CURDATE() - INTERVAL 2 MONTH, util.VN_CURDATE() + INTERVAL 1 MONTH, 1), + (2, 10, util.VN_CURDATE() - INTERVAL 2 DAY, util.VN_CURDATE() - INTERVAL 1 DAY, 2), + (3, 15, util.VN_CURDATE() + INTERVAL 3 DAY, util.VN_CURDATE() + INTERVAL 2 WEEK, 3), + (2, 10, util.VN_CURDATE() + INTERVAL 2 MONTH, NULL, 5), + (4, 8, util.VN_CURDATE() - INTERVAL 3 MONTH, NULL, NULL); + INSERT INTO `vn`.`expeditionBoxVol`(`boxFk`, `m3`, `ratio`) VALUES (71,0.141,1); @@ -1477,7 +1500,8 @@ INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseO (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5), (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6), (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7), - (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10); + (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10), + (10, DATE_ADD(util.VN_CURDATE(), INTERVAL + 5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10); INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `isRaid`, `evaNotes`) VALUES @@ -1488,7 +1512,9 @@ INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed (5, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 0, 442, 'IN2005', 'Movement 5', 0, 0, 'observation five'), (6, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 6, 0, 442, 'IN2006', 'Movement 6', 0, 0, 'observation six'), (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 0, 'observation seven'), - (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, 1, ''); + (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, 1, ''), + (9, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, 1, ''), + (10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, 1, ''); INSERT INTO `bs`.`waste`(`buyer`, `year`, `week`, `family`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleWaste`, `rate`) VALUES @@ -3232,7 +3258,6 @@ INSERT IGNORE INTO vn.itemType workerFk = 103, isInventory = TRUE, life = 10, - density = 250, itemPackingTypeFk = NULL, temperatureFk = 'warm'; diff --git a/db/routines/account/triggers/mailAliasAccount_afterDelete.sql b/db/routines/account/triggers/mailAliasAccount_afterDelete.sql new file mode 100644 index 000000000..83af7169c --- /dev/null +++ b/db/routines/account/triggers/mailAliasAccount_afterDelete.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_afterDelete` + AFTER DELETE ON `mailAliasAccount` + FOR EACH ROW +BEGIN + INSERT INTO userLog + SET `action` = 'delete', + `changedModel` = 'MailAliasAccount', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/account/triggers/mailAliasAccount_beforeInsert.sql b/db/routines/account/triggers/mailAliasAccount_beforeInsert.sql new file mode 100644 index 000000000..a435832f2 --- /dev/null +++ b/db/routines/account/triggers/mailAliasAccount_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_beforeInsert` + BEFORE INSERT ON `mailAliasAccount` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/account/triggers/mailAliasAccount_beforeUpdate.sql b/db/routines/account/triggers/mailAliasAccount_beforeUpdate.sql new file mode 100644 index 000000000..471a34900 --- /dev/null +++ b/db/routines/account/triggers/mailAliasAccount_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_beforeUpdate` + BEFORE UPDATE ON `mailAliasAccount` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/bi/procedures/rutasAnalyze.sql b/db/routines/bi/procedures/rutasAnalyze.sql index 5f0d55c7a..e277968bf 100644 --- a/db/routines/bi/procedures/rutasAnalyze.sql +++ b/db/routines/bi/procedures/rutasAnalyze.sql @@ -59,7 +59,7 @@ BEGIN JOIN vn.saleComponent sc ON sc.saleFk = s.id JOIN vn.component c ON c.id = sc.componentFk JOIN vn.componentType ct ON ct.id = c.typeFk - WHERE ct.code = 'FREIGHT' + WHERE ct.code = 'freight' AND r.created BETWEEN vDatedFrom AND vDatedTo GROUP BY r.id ) sub ON sub.routeFk = r.Id_Ruta diff --git a/db/routines/bi/views/tarifa_componentes_series.sql b/db/routines/bi/views/tarifa_componentes_series.sql index f231ae420..ed2f8e29a 100644 --- a/db/routines/bi/views/tarifa_componentes_series.sql +++ b/db/routines/bi/views/tarifa_componentes_series.sql @@ -2,7 +2,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `bi`.`tarifa_componentes_series` AS SELECT `ct`.`id` AS `tarifa_componentes_series_id`, - `ct`.`type` AS `Serie`, + `ct`.`name` AS `Serie`, `ct`.`isBase` AS `base`, `ct`.`isMargin` AS `margen` FROM `vn`.`componentType` `ct` diff --git a/db/routines/cache/procedures/availableNoRaids_refresh.sql b/db/routines/cache/procedures/availableNoRaids_refresh.sql index 383e35436..37715d270 100644 --- a/db/routines/cache/procedures/availableNoRaids_refresh.sql +++ b/db/routines/cache/procedures/availableNoRaids_refresh.sql @@ -117,7 +117,7 @@ proc: BEGIN )sub GROUP BY sub.itemFk; - DROP TEMPORARY TABLE tmp.itemCalc, tItemRange; + DROP TEMPORARY TABLE tmp.itemCalc, tItemRange, tmp.itemList; CALL cache_calc_end (vCalc); END$$ DELIMITER ; diff --git a/db/routines/cache/procedures/available_refresh.sql b/db/routines/cache/procedures/available_refresh.sql index d0939e568..abf023a41 100644 --- a/db/routines/cache/procedures/available_refresh.sql +++ b/db/routines/cache/procedures/available_refresh.sql @@ -121,7 +121,7 @@ proc: BEGIN )sub GROUP BY sub.itemFk; - DROP TEMPORARY TABLE tmp.itemCalc, itemRange; + DROP TEMPORARY TABLE tmp.itemCalc, itemRange, tmp.itemList; CALL cache_calc_end (vCalc); END$$ DELIMITER ; diff --git a/db/routines/cache/procedures/visible_refresh.sql b/db/routines/cache/procedures/visible_refresh.sql index 63b42dfd9..78d23dbfb 100644 --- a/db/routines/cache/procedures/visible_refresh.sql +++ b/db/routines/cache/procedures/visible_refresh.sql @@ -1,13 +1,13 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `cache`.`visible_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT) -proc: BEGIN +proc:BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN CALL cache_calc_unlock (v_calc); RESIGNAL; END; - CALL cache_calc_start (v_calc, v_refresh, 'visible', v_warehouse); + CALL cache_calc_start (v_calc, v_refresh, 'visible', v_warehouse); IF !v_refresh THEN LEAVE proc; @@ -15,22 +15,23 @@ proc: BEGIN -- Calculamos el stock hasta ayer - CALL `cache`.stock_refresh(false); + CALL cache.stock_refresh(false); CREATE OR REPLACE TEMPORARY TABLE tmp.itemVisible (PRIMARY KEY (item_id)) ENGINE = MEMORY - SELECT item_id, amount stock, amount visible FROM `cache`.stock + SELECT item_id, amount stock, amount visible + FROM cache.stock WHERE warehouse_id = v_warehouse; -- Calculamos los movimientos confirmados de hoy - CALL vn.item_GetVisible(v_warehouse, NULL); + CALL vn.item_calcVisible(NULL, v_warehouse); DELETE FROM visible WHERE calc_id = v_calc; INSERT INTO visible (calc_id, item_id,visible) SELECT v_calc, item_id, visible FROM tmp.itemVisible; - CALL cache_calc_end (v_calc); + CALL cache_calc_end (v_calc); DROP TEMPORARY TABLE tmp.itemVisible; END$$ diff --git a/db/routines/edi/procedures/ekt_refresh.sql b/db/routines/edi/procedures/ekt_refresh.sql index 0e9ed7d3c..8ba438c0a 100644 --- a/db/routines/edi/procedures/ekt_refresh.sql +++ b/db/routines/edi/procedures/ekt_refresh.sql @@ -7,7 +7,6 @@ BEGIN */ DECLARE vRewriteKop INT DEFAULT NULL; DECLARE vTruncatePutOrder INT DEFAULT NULL; - DECLARE vBarcode CHAR(15) DEFAULT NULL; DECLARE vKop INT; DECLARE vPutOrderFk BIGINT; @@ -16,17 +15,6 @@ BEGIN FROM ekt WHERE id = vSelf; - -- Generates the barcode - - SELECT CONCAT( - LPAD(IFNULL(auction,0), 3, 0), - LPAD(IFNULL(klo, 99), 2, 0), - LPAD(DAYOFYEAR(fec), 3, 0), - COALESCE(agj, RIGHT(batchNumber,7), id)) - INTO vBarcode - FROM ekt - WHERE id = vSelf; - -- Rewrites the kop parameter IF vKop IS NULL THEN @@ -46,10 +34,9 @@ BEGIN -- Refresh EKT - UPDATE ekt SET - barcode = vBarcode - ,kop = vKop - ,putOrderFk = vTruncatePutOrder + UPDATE ekt + SET kop = vKop, + putOrderFk = vTruncatePutOrder WHERE id = vSelf; END$$ DELIMITER ; diff --git a/db/routines/edi/views/ektRecent.sql b/db/routines/edi/views/ektRecent.sql index 3e41490ab..66ff7875e 100644 --- a/db/routines/edi/views/ektRecent.sql +++ b/db/routines/edi/views/ektRecent.sql @@ -2,7 +2,6 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `edi`.`ektRecent` AS SELECT `e`.`id` AS `id`, - `e`.`barcode` AS `barcode`, `e`.`entryYear` AS `entryYear`, `e`.`batchNumber` AS `batchNumber`, `e`.`deliveryNumber` AS `deliveryNumber`, diff --git a/db/routines/hedera/procedures/item_calcCatalog.sql b/db/routines/hedera/procedures/item_calcCatalog.sql index e72c2fd06..fae89bd5c 100644 --- a/db/routines/hedera/procedures/item_calcCatalog.sql +++ b/db/routines/hedera/procedures/item_calcCatalog.sql @@ -25,11 +25,7 @@ BEGIN JOIN vn.warehouse w ON w.id = p.warehouseFk ORDER BY warehouseFk, `grouping`; - DROP TEMPORARY TABLE - tmp.ticketCalculateItem, - tmp.ticketComponentPrice, - tmp.ticketComponent, - tmp.ticketLot, - tmp.zoneGetShipped; + CALL vn.ticketCalculatePurge(); + DROP TEMPORARY TABLE tmp.item; END$$ DELIMITER ; diff --git a/db/routines/hedera/procedures/order_addItem.sql b/db/routines/hedera/procedures/order_addItem.sql index d9c15c0eb..f690f9aa6 100644 --- a/db/routines/hedera/procedures/order_addItem.sql +++ b/db/routines/hedera/procedures/order_addItem.sql @@ -56,11 +56,23 @@ BEGIN CALL util.throw ('ORDER_ROW_UNAVAILABLE'); END IF; - SELECT IFNULL(minQuantity, 0) INTO vMinQuantity - FROM vn.item - WHERE id = vItem; + WITH itemMinQuantityPriority AS ( + SELECT quantity, + ROW_NUMBER() OVER ( + PARTITION BY itemFk + ORDER BY warehouseFk IS NULL + ) priority + FROM vn.itemMinimumQuantity + WHERE itemFk = vItem + AND `started` <= vShipment + AND (`ended` >= vShipment OR `ended` IS NULL) + AND (warehouseFk = vWarehouse OR warehouseFk IS NULL) + ) + SELECT quantity INTO vMinQuantity + FROM itemMinQuantityPriority + WHERE priority = 1; - IF vAmount < LEAST(vMinQuantity, vAvailable) THEN + IF vAmount < LEAST(IFNULL(vMinQuantity, 0), vAvailable) THEN CALL util.throw ('quantityLessThanMin'); END IF; diff --git a/db/routines/vn/events/claim_changeState.sql b/db/routines/vn/events/claim_changeState.sql new file mode 100644 index 000000000..5d94170a0 --- /dev/null +++ b/db/routines/vn/events/claim_changeState.sql @@ -0,0 +1,22 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`claim_changeState` + ON SCHEDULE EVERY 1 DAY + STARTS '2024-06-06 07:52:46.000' + ON COMPLETION PRESERVE + ENABLE +DO BEGIN + + DECLARE vClaimState INT; + + SELECT id INTO vClaimState + FROM claimState cs + WHERE cs.code = 'canceled'; + + UPDATE claim c + JOIN claimState cs ON cs.id = c.claimStateFk + SET c.claimStateFk = vClaimState + WHERE c.created < util.VN_CURDATE() - INTERVAL 2 MONTH + AND cs.code IN('incomplete','coming','waiting','out'); + +END$$ +DELIMITER ; diff --git a/db/routines/vn/functions/ticket_isProblemCalcNeeded.sql b/db/routines/vn/functions/ticket_isProblemCalcNeeded.sql new file mode 100644 index 000000000..4974a8c76 --- /dev/null +++ b/db/routines/vn/functions/ticket_isProblemCalcNeeded.sql @@ -0,0 +1,27 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_isProblemCalcNeeded`( + vSelf INT +) + RETURNS BOOL + DETERMINISTIC +BEGIN +/** + * Check if the ticket requires to update column vn.ticket.problem + * + * @param vSelf Id ticket + * @return BOOL + */ + DECLARE vIsProblemCalcNeeded BOOL; + + SELECT COUNT(*) INTO vIsProblemCalcNeeded + FROM ticket t + JOIN client c ON c.id = t.clientFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE t.id = vSelf + AND dm.code IN ('AGENCY','DELIVERY','PICKUP') + AND c.typeFk = 'normal'; + + RETURN vIsProblemCalcNeeded; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/XDiario_check.sql b/db/routines/vn/procedures/XDiario_check.sql index 0fb1c410d..ef969924b 100644 --- a/db/routines/vn/procedures/XDiario_check.sql +++ b/db/routines/vn/procedures/XDiario_check.sql @@ -6,19 +6,6 @@ BEGIN * identificando y notificando los asientos descuadrados * y ajustando los saldos en caso necesario. */ - INSERT INTO mail (receiver, subject, body) - SELECT 'cau@verdnatura.es', - 'Asientos descuadrados', - GROUP_CONCAT(CONCAT(' Asiento: ', ASIEN, ' - Importe:', recon) SEPARATOR ' | \n') - FROM ( - SELECT ASIEN, - SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon - FROM XDiario - WHERE NOT enlazado - GROUP BY ASIEN - HAVING ABS(SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0))) > 0.01 - ) sub - HAVING COUNT(*); UPDATE XDiario xd JOIN ( diff --git a/db/routines/vn/procedures/address_updateCoordinates.sql b/db/routines/vn/procedures/address_updateCoordinates.sql new file mode 100644 index 000000000..bdeb886df --- /dev/null +++ b/db/routines/vn/procedures/address_updateCoordinates.sql @@ -0,0 +1,25 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`address_updateCoordinates`( + vTicketFk INT, + vLongitude INT, + vLatitude INT) +BEGIN +/** + * Actualiza las coordenadas de una direcci贸n. + * + * @param vTicketFk Id del ticket + * @param vLongitude Longitud de la direcci贸n + * @param vLatitude Latitud de la direcci贸n + */ + DECLARE vAddressFK INT; + + SELECT addressFK INTO vAddressFK + FROM ticket + WHERE id = vTicketFk; + + UPDATE address + SET longitude = vLongitude, + latitude = vLatitude + WHERE id = vAddressFK; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/buyUltimate.sql b/db/routines/vn/procedures/buyUltimate.sql index 4346ef640..98b16cbc0 100644 --- a/db/routines/vn/procedures/buyUltimate.sql +++ b/db/routines/vn/procedures/buyUltimate.sql @@ -1,5 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`(vWarehouseFk SMALLINT, vDated DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`( + vWarehouseFk SMALLINT, + vDated DATE +) BEGIN /** * Calcula las 煤ltimas compras realizadas hasta una fecha @@ -19,21 +22,22 @@ BEGIN FROM cache.last_buy WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL; - CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated); + IF vDated >= util.VN_CURDATE() THEN + CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated); - REPLACE INTO tmp.buyUltimate - SELECT itemFk, buyFk, warehouseFk, landed landing - FROM tmp.buyUltimateFromInterval - WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) - AND landed <= vDated - AND NOT isIgnored; - - INSERT IGNORE INTO tmp.buyUltimate - SELECT itemFk, buyFk, warehouseFk, landed landing - FROM tmp.buyUltimateFromInterval - WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) - AND landed > vDated - ORDER BY isIgnored = FALSE DESC; + REPLACE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk, landed landing + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed <= vDated + AND NOT isIgnored; + INSERT IGNORE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk, landed landing + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed > vDated + ORDER BY isIgnored = FALSE DESC; + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/buyUltimateFromInterval.sql b/db/routines/vn/procedures/buyUltimateFromInterval.sql index e264b500d..5879b58e1 100644 --- a/db/routines/vn/procedures/buyUltimateFromInterval.sql +++ b/db/routines/vn/procedures/buyUltimateFromInterval.sql @@ -1,5 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInterval`(vWarehouseFk SMALLINT, vStarted DATE, vEnded DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInterval`( + vWarehouseFk SMALLINT, + vStarted DATE, + vEnded DATE +) BEGIN /** * Calcula las 煤ltimas compras realizadas @@ -21,12 +25,13 @@ BEGIN -- Item DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval; CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval - (PRIMARY KEY (itemFk, warehouseFk), INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk)) + (PRIMARY KEY (itemFk, warehouseFk), + INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk)) ENGINE = MEMORY SELECT itemFk, warehouseFk, buyFk, - MAX(landed) landed, + landed, isIgnored FROM (SELECT b.itemFk, t.warehouseInFk warehouseFk, @@ -45,93 +50,117 @@ BEGIN INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed > vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.price2 > 0 - AND NOT b.isIgnored - GROUP BY itemFk, warehouseInFk; + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed > vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vStarted AND vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.quantity = 0 - GROUP BY itemFk, warehouseInFk; + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.quantity = 0 + ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; -- ItemOriginal INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) SELECT itemFk, - warehouseFk, - buyFk, - MAX(landed) landed, - isIgnored - FROM (SELECT b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - itemOriginalFk, - b.isIgnored - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vStarted AND vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.price2 > 0 - AND NOT b.isIgnored - AND b.quantity > 0 - AND itemOriginalFk - ORDER BY t.landed DESC, b.id DESC - LIMIT 10000000000000000000) sub - GROUP BY itemOriginalFk, warehouseFk; + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + itemOriginalFk, + b.isIgnored + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + AND b.quantity > 0 + AND itemOriginalFk + ORDER BY t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed > vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + AND itemOriginalFk + ORDER BY t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed > vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.price2 > 0 - AND NOT b.isIgnored - AND itemOriginalFk - GROUP BY itemOriginalFk, warehouseInFk; - - INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vStarted AND vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.quantity = 0 - AND itemOriginalFk - GROUP BY itemOriginalFk, warehouseInFk; + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM + (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.quantity = 0 + AND itemOriginalFk + ORDER BY t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/catalog_calculate.sql b/db/routines/vn/procedures/catalog_calculate.sql index bb52020df..963e33507 100644 --- a/db/routines/vn/procedures/catalog_calculate.sql +++ b/db/routines/vn/procedures/catalog_calculate.sql @@ -45,8 +45,7 @@ BEGIN CALL catalog_componentPrepare(); - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem( + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem( itemFk INT(11) NOT NULL, available INT(11), producer VARCHAR(50), @@ -60,11 +59,11 @@ BEGIN price DECIMAL(10,2), priceKg DECIMAL(10,2), `grouping` INT(10) UNSIGNED, + minQuantity INT(10) UNSIGNED, PRIMARY KEY `itemFk` (`itemFk`) ) ENGINE = MEMORY DEFAULT CHARSET=utf8; OPEN cTravelTree; - l: LOOP SET vDone = FALSE; FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; @@ -136,7 +135,7 @@ BEGIN CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); - INSERT INTO tmp.ticketCalculateItem ( + INSERT INTO tmp.ticketCalculateItem( itemFk, available, producer, @@ -149,9 +148,9 @@ BEGIN origin, price, priceKg, - `grouping`) - SELECT - tl.itemFk, + `grouping`, + minQuantity) + SELECT tl.itemFk, SUM(tl.available) available, p.name producer, i.name item, @@ -163,7 +162,8 @@ BEGIN o.code origin, bl.price, bl.priceKg, - bl.`grouping` + bl.`grouping`, + mq.quantity FROM tmp.ticketLot tl JOIN item i ON tl.itemFk = i.id LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible @@ -179,12 +179,28 @@ BEGIN ) sub GROUP BY itemFk ) bl ON bl.itemFk = tl.itemFk - WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk + LEFT JOIN ( + WITH itemMinQuantityPriority AS ( + SELECT itemFk, + quantity, + ROW_NUMBER() OVER ( + PARTITION BY itemFk + ORDER BY warehouseFk IS NULL + ) priority + FROM vn.itemMinimumQuantity + WHERE `started` <= vShipped + AND (`ended` >= vShipped OR `ended` IS NULL) + AND (warehouseFk = vWarehouseFk OR warehouseFk IS NULL) + ) + SELECT itemFk, quantity + FROM itemMinQuantityPriority + WHERE priority = 1 + ) mq ON mq.itemFk = tl.itemFk + WHERE tl.zoneFk = vZoneFk + AND tl.warehouseFk = vWarehouseFk GROUP BY tl.itemFk ON DUPLICATE KEY UPDATE available = available + VALUES(available); - END LOOP; - CLOSE cTravelTree; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/client_create.sql b/db/routines/vn/procedures/client_create.sql index d5d7258a1..f2321e129 100644 --- a/db/routines/vn/procedures/client_create.sql +++ b/db/routines/vn/procedures/client_create.sql @@ -34,20 +34,25 @@ BEGIN DECLARE vIsTaxDataChecked TINYINT(1); DECLARE vHasCoreVnl BOOLEAN; DECLARE vMandateTypeFk INT; + DECLARE vHasDailyInvoice BOOLEAN; - SELECT defaultPayMethodFk, - defaultDueDay, - defaultCredit, - defaultIsTaxDataChecked, - defaultHasCoreVnl, - defaultMandateTypeFk + SELECT cc.defaultPayMethodFk, + cc.defaultDueDay, + cc.defaultCredit, + cc.defaultIsTaxDataChecked, + cc.defaultHasCoreVnl, + cc.defaultMandateTypeFk, + c.hasDailyInvoice INTO vPayMethodFk, vDueDay, vDefaultCredit, vIsTaxDataChecked, vHasCoreVnl, - vMandateTypeFk - FROM clientConfig; + vMandateTypeFk, + vHasDailyInvoice + FROM clientConfig cc + LEFT JOIN province p ON p.id = vProvinceFk + LEFT JOIN country c ON c.id = p.countryFk; INSERT INTO `client` SET id = vUserFk, @@ -65,7 +70,8 @@ BEGIN credit = vDefaultCredit, isTaxDataChecked = vIsTaxDataChecked, hasCoreVnl = vHasCoreVnl, - isEqualizated = FALSE + isEqualizated = FALSE, + hasDailyInvoice = vHasDailyInvoice ON duplicate KEY UPDATE payMethodFk = vPayMethodFk, dueDay = vDueDay, diff --git a/db/routines/vn/procedures/collection_setParking.sql b/db/routines/vn/procedures/collection_setParking.sql index 73aa87bfb..5f6ca75da 100644 --- a/db/routines/vn/procedures/collection_setParking.sql +++ b/db/routines/vn/procedures/collection_setParking.sql @@ -1,15 +1,18 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_setParking`(IN `vCollectionFk` VARCHAR(8), IN `vParkingFk` INT) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_setParking`( + vSelf INT, + vParkingFk INT +) +BEGIN /** * Aparca una colecci贸n en un parking. * - * @param vCollectionFk Id de la colecci贸n - * @param vParkingFk Id del parking + * @param vSelf Id colecci贸n + * @param vParkingFk Id parking */ - REPLACE vn.ticketParking(ticketFk, parkingFk) + REPLACE ticketParking(ticketFk, parkingFk) SELECT tc.ticketFk, vParkingFk - FROM vn.ticketCollection tc - WHERE tc.collectionFk = vCollectionFk; + FROM ticketCollection tc + WHERE tc.collectionFk = vSelf; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/copyComponentsFromSaleList.sql b/db/routines/vn/procedures/copyComponentsFromSaleList.sql index 17cf487b1..8db8409f1 100644 --- a/db/routines/vn/procedures/copyComponentsFromSaleList.sql +++ b/db/routines/vn/procedures/copyComponentsFromSaleList.sql @@ -16,9 +16,9 @@ BEGIN SET @order = 0; - DROP TEMPORARY TABLE IF EXISTS tmp.newSaleList; + DROP TEMPORARY TABLE IF EXISTS tNewSaleList; - CREATE TEMPORARY TABLE tmp.newSaleList + CREATE TEMPORARY TABLE tNewSaleList SELECT id as saleFk, @order := @order + 1 as orden FROM vn.sale WHERE ticketFk = vTargetTicketFk @@ -28,7 +28,8 @@ BEGIN SELECT ns.saleFk, sc.componentFk, sc.value FROM vn.saleComponent sc JOIN tmp.saleList s ON s.saleFk = sc.saleFk - JOIN tmp.newSaleList ns ON ns.orden = s.orden; + JOIN tNewSaleList ns ON ns.orden = s.orden; + DROP TEMPORARY TABLE tNewSaleList; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql index a05a1fd92..c279fac65 100644 --- a/db/routines/vn/procedures/entry_isEditable.sql +++ b/db/routines/vn/procedures/entry_isEditable.sql @@ -18,7 +18,7 @@ BEGIN AND e.id = vSelf; IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN - CALL util.throw('Entry is not editable'); + CALL util.throw(CONCAT('Entry ', vSelf, ' is not editable')); END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index 2898141ea..eb07c12b7 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -13,60 +13,45 @@ BEGIN DECLARE vBuyStickers INT; DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE cur CURSOR FOR + DECLARE cur CURSOR FOR SELECT bb.id buyFk, FLOOR(ish.visible / ish.packing) ishStickers, bb.stickers buyStickers - FROM vn.itemShelving ish + FROM itemShelving ish JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b - WHERE b.entryFk = vFromEntryFk - ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - AND bb.stickers >= FLOOR(ish.visible / ish.packing) - WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci - GROUP BY ish.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Cantidades de la matr铆cula que exceden la de las entradas - SELECT ish.itemFk, - i.longName, - FLOOR(ish.visible / ish.packing) AS etiEnMatricula, - bb.stickers etiEnEntrada - FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - LEFT JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + FROM buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci - AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing) + AND bb.stickers >= FLOOR(ish.visible / ish.packing) + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + AND NOT ish.isSplit GROUP BY ish.id; - + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + OPEN cur; read_loop: LOOP SET vDone = FALSE; FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; - + IF vDone THEN LEAVE read_loop; END IF; - + IF vIshStickers = vBuyStickers THEN - UPDATE vn.buy + UPDATE buy SET entryFk = vToEntryFk WHERE id = vBuyFk; ELSE - UPDATE vn.buy + UPDATE buy SET stickers = stickers - vIshStickers, quantity = stickers * packing WHERE id = vBuyFk; - - INSERT INTO vn.buy(entryFk, + + INSERT INTO buy(entryFk, itemFk, quantity, buyingValue, @@ -117,13 +102,16 @@ BEGIN weight, deliveryFk, itemOriginalFk - FROM vn.buy + FROM buy WHERE id = vBuyFk; UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); END IF; - END LOOP; + UPDATE itemShelving + SET isSplit = TRUE + WHERE shelvingFk = vShelvingFk; + END LOOP; CLOSE cur; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index cd838861a..c194a774d 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -13,20 +13,32 @@ BEGIN * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo */ DECLARE vFiscalYear INT; - DECLARE vHasDistinctTransactions INT; + DECLARE vDistinctTransactions INT; + DECLARE vHasRepeatedTransactions BOOL; - SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions + SELECT COUNT(DISTINCT iit.transactionTypeSageFk) INTO vDistinctTransactions FROM invoiceIn ii JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id JOIN invoiceInSerial iis ON iis.code = ii.serial - WHERE ii.id = vSelf + WHERE iit.invoiceInFk = vSelf AND iis.taxAreaFk = 'CEE' - AND transactionTypeSageFk; + AND iit.transactionTypeSageFk; - IF vHasDistinctTransactions > 1 THEN + IF vDistinctTransactions > 1 THEN CALL util.throw ('This invoice does not allow different types of transactions'); END IF; + SELECT TRUE INTO vHasRepeatedTransactions + FROM invoiceInTax + WHERE invoiceInFk = vSelf + GROUP BY transactionTypeSageFk + HAVING COUNT(transactionTypeSageFk) > 1 + LIMIT 1; + + IF vHasRepeatedTransactions THEN + CALL util.throw ('This invoice contains repeated types of transactions'); + END IF; + CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn ENGINE = MEMORY SELECT ii.bookEntried, diff --git a/db/routines/vn/procedures/itemShelving_inventory.sql b/db/routines/vn/procedures/itemShelving_inventory.sql index 73e438fbb..f4b8ae165 100644 --- a/db/routines/vn/procedures/itemShelving_inventory.sql +++ b/db/routines/vn/procedures/itemShelving_inventory.sql @@ -59,5 +59,7 @@ BEGIN WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo AND p.sectorFk = vSectorFk ORDER BY p.pickingOrder; + + DROP TEMPORARY TABLE tmp.stockMisfit; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/item_GetVisible.sql b/db/routines/vn/procedures/item_GetVisible.sql deleted file mode 100644 index ca5e43107..000000000 --- a/db/routines/vn/procedures/item_GetVisible.sql +++ /dev/null @@ -1,43 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_GetVisible`(vWarehouse SMALLINT, vItem INT) -BEGIN - DECLARE vTomorrow DATETIME DEFAULT TIMESTAMPADD(DAY, 1, util.VN_CURDATE()); - - INSERT INTO tmp.itemVisible (item_id, visible) - SELECT item_id, SUM(amount) amount - FROM ( - SELECT i.itemFk AS item_id, quantity AS amount - FROM itemTicketOut i - LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk - JOIN state s ON s.id = ts.stateFk - LEFT JOIN (SELECT DISTINCT saleFk - FROM saleTracking st - JOIN state s ON s.id = st.stateFk - WHERE st.created > util.VN_CURDATE() - AND (s.isPicked OR st.isChecked) - ) stPrevious ON `stPrevious`.`saleFk` = i.saleFk - WHERE i.warehouseFk = vWarehouse - AND (vItem IS NULL OR i.itemFk = vItem) - AND (s.isPicked OR i.reserved OR stPrevious.saleFk ) - AND i.shipped >= util.VN_CURDATE() AND i.shipped < vTomorrow - UNION ALL - SELECT iei.itemFk, quantity - FROM itemEntryIn iei - WHERE (iei.isReceived != FALSE /*OR ip.modificationDate > util.VN_CURDATE()*/) - AND iei.landed >= util.VN_CURDATE() AND iei.landed < vTomorrow - AND iei.warehouseInFk = vWarehouse - AND (vItem IS NULL OR iei.itemFk = vItem) - AND iei.isVirtualStock is FALSE - UNION ALL - SELECT itemFk, quantity - FROM itemEntryOut - WHERE isDelivered != FALSE - AND shipped >= util.VN_CURDATE() AND shipped < vTomorrow - AND warehouseOutFk = vWarehouse - AND (vItem IS NULL OR itemFk = vItem) - ) t - GROUP BY item_id - ON DUPLICATE KEY UPDATE - visible = IFNULL(stock,0) + VALUES(visible); -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/item_calcVisible.sql b/db/routines/vn/procedures/item_calcVisible.sql new file mode 100644 index 000000000..820e73a7e --- /dev/null +++ b/db/routines/vn/procedures/item_calcVisible.sql @@ -0,0 +1,56 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_calcVisible`( + vSelf INT, + vWarehouseFk INT +) +BEGIN +/** + * Calcula el visible de un art铆culo o de todos. + * + * @param vWarehouse Warehouse id + * @param vSelf Item id + * @param tmp.itemVisible(item_id, stock, visible) + */ + DECLARE vDated DATE DEFAULT util.VN_CURDATE(); + DECLARE vTomorrow DATETIME DEFAULT util.tomorrow(); + + INSERT INTO tmp.itemVisible(item_id, visible) + SELECT itemFk, SUM(quantity) + FROM ( + SELECT i.itemFk, i.quantity + FROM itemTicketOut i + LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk + JOIN `state` s ON s.id = ts.stateFk + LEFT JOIN ( + SELECT DISTINCT st.saleFk + FROM saleTracking st + JOIN state s ON s.id = st.stateFk + WHERE st.created > vDated + AND (s.isPicked OR st.isChecked) + ) stPrevious ON `stPrevious`.`saleFk` = i.saleFk + WHERE IFNULL(vWarehouseFk, i.warehouseFk) = i.warehouseFk + AND (vSelf IS NULL OR i.itemFk = vSelf) + AND (s.isPicked OR i.reserved OR stPrevious.saleFk) + AND i.shipped >= vDated AND i.shipped < vTomorrow + UNION ALL + SELECT itemFk, quantity + FROM itemEntryIn + WHERE isReceived + AND landed >= vDated AND landed < vTomorrow + AND IFNULL(vWarehouseFk, warehouseInFk) = warehouseInFk + AND (vSelf IS NULL OR itemFk = vSelf) + AND NOT isVirtualStock + UNION ALL + SELECT itemFk, quantity + FROM itemEntryOut + WHERE isDelivered + AND shipped >= vDated + AND shipped < vTomorrow + AND IFNULL(vWarehouseFk, warehouseOutFk) = warehouseOutFk + AND (vSelf IS NULL OR itemFk = vSelf) + ) t + GROUP BY itemFk + ON DUPLICATE KEY UPDATE + visible = IFNULL(stock, 0) + VALUES(visible); +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql index a4942af6f..0de59b478 100644 --- a/db/routines/vn/procedures/item_getBalance.sql +++ b/db/routines/vn/procedures/item_getBalance.sql @@ -2,94 +2,84 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getBalance`( vItemFk INT, vWarehouseFk INT, - vDate DATETIME + vDated DATETIME ) BEGIN /** - * @vItemFk item a buscar - * @vWarehouseFk almacen donde buscar - * @vDate Si la fecha es null, muestra el hist贸rico desde el inventario. - * Si la fecha no es null, muestra hist贸rico desde la fecha de vDate. + * Calcula el balance de un art铆culo. + * + * @vItemFk Id de art铆culo + * @vWarehouseFk Id de almac茅n + * @vDated Fecha a calcular, si es NULL muestra el hist贸rico desde el inventario */ - DECLARE vDateInventory DATETIME; + DECLARE vDateInventory DATETIME + DEFAULT ( + SELECT IF(vDated, uc.mockUtcTime, c.inventoried) + FROM config c + JOIN util.config uc + ); + DECLARE vSupplierInventoryFk INT + DEFAULT (SELECT supplierFk FROM inventoryConfig); - IF vDate IS NULL THEN - SELECT inventoried INTO vDateInventory - FROM config; - ELSE - SELECT mockUtcTime INTO vDateInventory - FROM util.config; + IF NOT vSupplierInventoryFk OR NOT vDateInventory THEN + CALL util.throw('Config variables are not set'); END IF; - CREATE OR REPLACE TEMPORARY TABLE tItemDiary( - shipped DATE, - `in` INT(11), - `out` INT(11), - alertLevel INT(11), - stateName VARCHAR(20), - `name` VARCHAR(50), - reference VARCHAR(50), - origin INT(11), - clientFk INT(11), - isPicked INT(11), - isTicket TINYINT(1), - lineFk INT(11), - `order` TINYINT(3) UNSIGNED, - clientType VARCHAR(20), - claimFk INT(10) UNSIGNED, - inventorySupplierFk INT(10) - ); - - INSERT INTO tItemDiary + CREATE OR REPLACE TEMPORARY TABLE tItemDiary + ENGINE = MEMORY WITH entriesIn AS ( - SELECT tr.landed shipped, + SELECT 'entry' originType, + e.id originId, + tr.landed shipped, b.quantity `in`, NULL `out`, st.alertLevel , st.name stateName, - s.name `name`, e.invoiceNumber reference, - e.id origin, - s.id clientFk, + 'supplier' entityType, + s.id entityId, + s.name entityName, IF(st.`code` = 'DELIVERED', TRUE, FALSE) isPicked, FALSE isTicket, b.id lineFk, NULL `order`, NULL clientType, NULL claimFk, - ec.inventorySupplierFk + vSupplierInventoryFk inventorySupplierFk FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.travel tr ON tr.id = e.travelFk JOIN vn.supplier s ON s.id = e.supplierFk - JOIN vn.state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() + JOIN vn.state st ON st.`code` = IF(tr.landed < util.VN_CURDATE() OR (util.VN_CURDATE() AND tr.isReceived), 'DELIVERED', 'FREE') - JOIN vn.entryConfig ec WHERE tr.landed >= vDateInventory - AND vWarehouseFk = tr.warehouseInFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND tr.warehouseInFk = vWarehouseFk + AND (s.id <> vSupplierInventoryFk OR vDated IS NULL) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable AND NOT e.isRaid - ), entriesOut AS ( - SELECT tr.shipped, + ), + entriesOut AS ( + SELECT 'entry', + e.id originType, + tr.shipped, NULL, b.quantity, st.alertLevel, st.name stateName, - s.name , e.invoiceNumber, - e.id entryFk, - s.id supplierFk, + 'supplier' entityType, + s.id entityId, + s.name, IF(st.`code` = 'DELIVERED' , TRUE, FALSE), FALSE isTicket, b.id, NULL `order`, NULL clientType, NULL claimFk, - ec.inventorySupplierFk + vSupplierInventoryFk FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.travel tr ON tr.id = e.travelFk @@ -99,86 +89,108 @@ BEGIN OR (tr.shipped = util.VN_CURDATE() AND tr.isReceived), 'DELIVERED', 'FREE') - JOIN vn.entryConfig ec WHERE tr.shipped >= vDateInventory - AND vWarehouseFk = tr.warehouseOutFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND tr.warehouseOutFk = vWarehouseFk + AND (s.id <> vSupplierInventoryFk OR vDated IS NULL) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable AND NOT w.isFeedStock AND NOT e.isRaid - ), sales AS ( - SELECT DATE(t.shipped) shipped, - s.quantity, - st2.alertLevel, - st2.name, - t.nickname, - t.refFk, - t.id ticketFk, - t.clientFk, - s.id saleFk, - st.`order`, - c.typeFk, - cb.claimFk - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id - LEFT JOIN vn.state st ON st.`code` = ts.`code` - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), - 'DELIVERED', - IF (t.shipped > util.dayEnd(util.VN_CURDATE()), - 'FREE', - IFNULL(ts.code, 'FREE'))) - LEFT JOIN vn.claimBeginning cb ON s.id = cb.saleFk - WHERE t.shipped >= vDateInventory - AND s.itemFk = vItemFk - AND vWarehouseFk = t.warehouseFk - ),sale AS ( - SELECT s.shipped, + ), + sales AS ( + WITH itemSales AS ( + SELECT DATE(t.shipped) shipped, + s.quantity, + st2.alertLevel, + st2.name, + t.refFk, + t.id ticketFk, + 'client' entityType, + t.clientFk entityId, + t.nickname, + s.id saleFk, + st.`order`, + c.typeFk, + cb.claimFk + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id + LEFT JOIN vn.state st ON st.code = ts.code + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), + 'DELIVERED', + IF (t.shipped > util.dayEnd(util.VN_CURDATE()), + 'FREE', + IFNULL(st.code, 'FREE'))) + LEFT JOIN vn.claimBeginning cb ON cb.saleFk = s.id + WHERE t.shipped >= vDateInventory + AND s.itemFk = vItemFk + AND t.warehouseFk = vWarehouseFk + ) + SELECT 'ticket', + s.ticketFk, + s.shipped, NULL `in`, s.quantity, s.alertLevel, s.name, - s.nickname, s.refFk, - s.ticketFk, - s.clientFk, - IF(stk.saleFk, TRUE, NULL), + s.entityType, + s.entityId, + s.nickname, + IF(stk.saleFk, TRUE, FALSE), TRUE, s.saleFk, s.`order`, s.typeFk, s.claimFk, NULL - FROM sales s + FROM itemSales s LEFT JOIN vn.state stPrep ON stPrep.`code` = 'PREPARED' LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.saleFk AND stk.stateFk = stPrep.id GROUP BY s.saleFk - ) SELECT shipped, - `in`, - `out`, - alertLevel, - stateName, - `name`, - reference, - origin, - clientFk, - isPicked, - isTicket, - lineFk, - `order`, - clientType, - claimFk, - inventorySupplierFk - FROM entriesIn + ), + orders AS ( + SELECT 'order' originType, + o.id originId, + r.shipment, + NULL 'in', + r.amount, + NULL alertLevel, + NULL stateName, + NULL invoiceNumber, + 'client' entityType, + c.id, + c.name, + FALSE, + FALSE isTicket, + NULL buyFk, + NULL 'order', + c.typeFk, + NULL claimFk, + NULL + FROM hedera.orderRow r + JOIN hedera.`order` o ON o.id = r.orderFk + JOIN vn.client c ON c.id = o.customer_id + WHERE r.shipment >= vDateInventory + AND r.warehouseFk = vWarehouseFk + AND r.created >= ( + SELECT SUBTIME(util.VN_NOW(), reserveTime) + FROM hedera.orderConfig + ) + AND NOT o.confirmed + AND r.itemFk = vItemFk + ) + SELECT * FROM entriesIn UNION ALL SELECT * FROM entriesOut UNION ALL - SELECT * FROM sale + SELECT * FROM sales + UNION ALL + SELECT * FROM orders ORDER BY shipped, - (inventorySupplierFk = clientFk) DESC, + (inventorySupplierFk = entityId) DESC, alertLevel DESC, isTicket, `order` DESC, @@ -186,19 +198,20 @@ BEGIN `in` DESC, `out` DESC; - IF vDate IS NULL THEN - + IF vDated IS NULL THEN SET @a := 0; SET @currentLineFk := 0; SET @shipped := ''; - SELECT DATE(@shipped:= t.shipped) shipped, + SELECT t.originType, + t.originId, + DATE(@shipped:= t.shipped) shipped, t.alertLevel, t.stateName, - t.origin, t.reference, - t.clientFk, - t.name, + t.entityType, + t.entityId, + t.entityName, t.`in` invalue, t.`out`, @a := @a + IFNULL(t.`in`, 0) - IFNULL(t.`out`, 0) balance, @@ -214,37 +227,41 @@ BEGIN t.`order` FROM tItemDiary t LEFT JOIN alertLevel a ON a.id = t.alertLevel; - ELSE SELECT IFNULL(SUM(IFNULL(`in`, 0)) - SUM(IFNULL(`out`, 0)), 0) INTO @a FROM tItemDiary - WHERE shipped < vDate; + WHERE shipped < vDated; - SELECT vDate shipped, - 0 alertLevel, - 0 stateName, - 0 origin, - '' reference, - 0 clientFk, + SELECT NULL originType, + NULL originId, + vDated shipped, + NULL alertLevel, + NULL stateName, + NULL reference, + NULL entityType, + NULL entityId, 'Inventario calculado', @a invalue, NULL `out`, @a balance, - 0 lastPreparedLineFk, - 0 isTicket, - 0 lineFk, - 0 isPicked, - 0 clientType, - 0 claimFk, + NULL lastPreparedLineFk, + NULL isTicket, + NULL lineFk, + NULL isPicked, + NULL clientType, + NULL claimFk, NULL `order` UNION ALL - SELECT shipped, + SELECT originType, + originId, + shipped, alertlevel, stateName, - origin, - reference, - clientFk, - name, `in`, + reference, + entityType, + entityId, + entityName, + `in`, `out`, @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0), 0, @@ -255,7 +272,7 @@ BEGIN claimFk, `order` FROM tItemDiary - WHERE shipped >= vDate; + WHERE shipped >= vDated; END IF; DROP TEMPORARY TABLE tItemDiary; diff --git a/db/routines/vn/procedures/item_getMinacum.sql b/db/routines/vn/procedures/item_getMinacum.sql index 7573759f7..a3ebedb12 100644 --- a/db/routines/vn/procedures/item_getMinacum.sql +++ b/db/routines/vn/procedures/item_getMinacum.sql @@ -76,5 +76,7 @@ BEGIN i.quantity amount FROM tmp.itemAtp i HAVING amount != 0; + + DROP TEMPORARY TABLE tmp.itemAtp; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 557d77bdf..72c543b40 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -63,7 +63,7 @@ BEGIN WHEN b.groupingMode = 'grouping' THEN b.grouping WHEN b.groupingMode = 'packing' THEN b.packing ELSE 1 - END AS minQuantity, + END minQuantity, v.visible located, b.price2 FROM vn.item i diff --git a/db/routines/vn/procedures/item_setVisibleDiscard.sql b/db/routines/vn/procedures/item_setVisibleDiscard.sql index 0a6c54971..a44d87333 100644 --- a/db/routines/vn/procedures/item_setVisibleDiscard.sql +++ b/db/routines/vn/procedures/item_setVisibleDiscard.sql @@ -6,7 +6,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setVisibleDisc vAddressFk INT) BEGIN /** - * Procedimiento para dar dar de baja/alta un item, si vAddressFk es NULL se entiende que se da de alta y se toma el addressFk de la configuraci贸n + * Procedimiento para dar dar de baja/alta un item, si vAdressFk es NULL + * se entiende que se da de alta y se toma el addressFk de la configuraci贸n * * @param vItemFk Identificador del 铆tem * @param vWarehouseFk id del warehouse diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 941ac6c3d..6cd584c6e 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -10,6 +10,7 @@ proc: BEGIN DECLARE vDateTo DATETIME; DECLARE vDateToTomorrow DATETIME; DECLARE vDefaultDayRange INT; + DECLARE vCalcFk INT; IF vDate < util.VN_CURDATE() THEN LEAVE proc; @@ -82,50 +83,18 @@ proc: BEGIN ai.sd = iic.quantity; -- C谩lculo del visible - CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT itemFk, SUM(quantity) visible - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk; + CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); - UPDATE tmp.itemInventory ai - JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id - SET ai.visible = ai.visible + ivc.visible; + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT item_id, visible + FROM cache.visible + WHERE calc_id = vCalcFk; + + UPDATE tmp.itemInventory it + JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id + SET it.visible = it.visible + ivc.visible; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc @@ -196,8 +165,8 @@ proc: BEGIN DROP TEMPORARY TABLE tmp.itemTravel, tmp.itemCalc, + tmp.itemAtp, tItemInventoryCalc, - tItemVisibleCalc, - tmp.itemAtp; + tItemVisibleCalc; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/productionSectorList.sql b/db/routines/vn/procedures/productionSectorList.sql index 5447f10d0..e1445ca52 100644 --- a/db/routines/vn/procedures/productionSectorList.sql +++ b/db/routines/vn/procedures/productionSectorList.sql @@ -104,5 +104,6 @@ BEGIN ) sub; DROP TEMPORARY TABLE tmp.whiteTicket; DROP TEMPORARY TABLE tmp.sectorTypeTicket; + DROP TEMPORARY TABLE tmp.productionBuffer; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/saleGroup_setParking.sql b/db/routines/vn/procedures/saleGroup_setParking.sql index 4872f74c6..551ca6386 100644 --- a/db/routines/vn/procedures/saleGroup_setParking.sql +++ b/db/routines/vn/procedures/saleGroup_setParking.sql @@ -1,17 +1,25 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleGroup_setParking`(IN `vSaleGroupFk` VARCHAR(8), IN `vParkingFk` INT) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleGroup_setParking`( + vSaleGroupFk VARCHAR(8), + vParkingFk INT +) +BEGIN /** - * Aparca una preparaci贸n previa en un parking + * Aparca una preparaci贸n previa en un parking. * * @param vSaleGroupFk id de la preparaci贸n previa * @param vParkingFk id del parking */ - UPDATE vn.saleGroup sg + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + + UPDATE saleGroup sg SET sg.parkingFk = vParkingFk WHERE sg.id = vSaleGroupFk - AND sg.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + AND sg.created >= util.VN_CURDATE() - INTERVAL 1 WEEK; - CALL vn.ticket_setNextState(vn.ticket_get(vSaleGroupFk)); + CALL ticket_setNextState(ticket_get(vSaleGroupFk)); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/sale_PriceFix.sql b/db/routines/vn/procedures/sale_PriceFix.sql index 8ffa77070..5f956cba8 100644 --- a/db/routines/vn/procedures/sale_PriceFix.sql +++ b/db/routines/vn/procedures/sale_PriceFix.sql @@ -8,7 +8,7 @@ BEGIN JOIN vn.component c ON c.id = sc.componentFk JOIN vn.componentType ct ON ct.id = c.typeFk WHERE s.ticketFk = vTicketFk - AND ct.`type` = 'otros'; + AND ct.code = 'other'; UPDATE vn.sale s JOIN ( diff --git a/db/routines/vn/procedures/sale_setProblem.sql b/db/routines/vn/procedures/sale_setProblem.sql index 20319cc3f..b0870089f 100644 --- a/db/routines/vn/procedures/sale_setProblem.sql +++ b/db/routines/vn/procedures/sale_setProblem.sql @@ -5,14 +5,32 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_setProblem`( BEGIN /** * Update column sale.problem with a problem code + * * @param vProblemCode Code to set or unset - * @table tmp.sale(saleFk, hasProblem) + * @table tmp.sale(saleFk, hasProblem, isProblemCalcNeeded) */ - UPDATE sale s - JOIN tmp.sale ts ON ts.saleFk = s.id - SET s.problem = CONCAT( - IF(ts.hasProblem, - CONCAT(s.problem, ',', vProblemCode), - REPLACE(s.problem, vProblemCode , ''))); + DECLARE vSaleFk INT; + DECLARE vHasProblem INT; + DECLARE vDone BOOL; + DECLARE vSaleList CURSOR FOR SELECT saleFk, hasProblem FROM tmp.sale; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vSaleList; + l: LOOP + SET vDone = FALSE; + FETCH vSaleList INTO vSaleFk, vHasProblem; + + IF vDone THEN + LEAVE l; + END IF; + + UPDATE sale + SET problem = CONCAT( + IF(vHasProblem, + CONCAT(problem, ',', vProblemCode), + REPLACE(problem, vProblemCode , ''))) + WHERE id = vSaleFk; + END LOOP; + CLOSE vSaleList; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/sale_setProblemComponentLack.sql b/db/routines/vn/procedures/sale_setProblemComponentLack.sql index 363663a00..aa5f5f1be 100644 --- a/db/routines/vn/procedures/sale_setProblemComponentLack.sql +++ b/db/routines/vn/procedures/sale_setProblemComponentLack.sql @@ -10,9 +10,13 @@ BEGIN * @param vSelf Id del sale */ CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk)) + (INDEX(saleFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT vSelf saleFk, sale_hasComponentLack(vSelf) hasProblem; + SELECT vSelf saleFk, + sale_hasComponentLack(vSelf) hasProblem, + ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded + FROM sale + WHERE id = vSelf; CALL sale_setProblem('hasComponentLack'); diff --git a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql index b911327dd..2ee49b656 100644 --- a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql +++ b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql @@ -10,11 +10,13 @@ BEGIN * @param vComponentFk Id component */ CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk)) + (INDEX(saleFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT saleFk, sale_hasComponentLack(saleFk)hasProblem + SELECT saleFk, + sale_hasComponentLack(saleFk) hasProblem, + ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded FROM ( - SELECT s.id saleFk + SELECT s.id saleFk, s.ticketFk FROM ticket t JOIN sale s ON s.ticketFk = t.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id diff --git a/db/routines/vn/procedures/sale_setProblemRounding.sql b/db/routines/vn/procedures/sale_setProblemRounding.sql index f14cd408f..f58d00799 100644 --- a/db/routines/vn/procedures/sale_setProblemRounding.sql +++ b/db/routines/vn/procedures/sale_setProblemRounding.sql @@ -11,9 +11,10 @@ BEGIN DECLARE vWarehouseFk INT; DECLARE vShipped DATE; DECLARE vQuantity INT; + DECLARE vIsProblemCalcNeeded BOOL; - SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity - INTO vItemFk, vWarehouseFk, vShipped, vQuantity + SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity, ticket_isProblemCalcNeeded(t.id) + INTO vItemFk, vWarehouseFk, vShipped, vQuantity, vIsProblemCalcNeeded FROM sale s JOIN ticket t ON t.id = s.ticketFk WHERE s.id = vSelf; @@ -21,7 +22,9 @@ BEGIN CALL buyUltimate(vWarehouseFk, vShipped); CREATE OR REPLACE TEMPORARY TABLE tmp.sale - SELECT vSelf saleFk, MOD(vQuantity, b.`grouping`) hasProblem + SELECT vSelf saleFk, + MOD(vQuantity, b.`grouping`) hasProblem, + vIsProblemCalcNeeded isProblemCalcNeeded FROM tmp.buyUltimate bu JOIN buy b ON b.id = bu.buyFk WHERE bu.itemFk = vItemFk; diff --git a/db/routines/vn/procedures/setParking.sql b/db/routines/vn/procedures/setParking.sql index d6def07de..1aa4f920a 100644 --- a/db/routines/vn/procedures/setParking.sql +++ b/db/routines/vn/procedures/setParking.sql @@ -1,6 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`setParking`(IN `vParam` VARCHAR(8), IN `vParkingCode` VARCHAR(8)) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`setParking`( + vParam VARCHAR(8), + vParkingCode VARCHAR(8) +) +BEGIN /** * Aparca una colecci贸n, un ticket, un saleGroup o un shelving en un parking * @@ -8,56 +11,41 @@ proc: BEGIN * @param vParkingCode c贸digo del parking */ DECLARE vParkingFk INT; - DECLARE vIsSaleGroup BOOL; - DECLARE vIsTicket BOOL; - DECLARE vIsCollection BOOL; + DECLARE vLastWeek DATE; - SET vParkingCode = replace(vParkingCode,' ',''); + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SET vParkingCode = REPLACE(vParkingCode, ' ', ''); SELECT id INTO vParkingFk - FROM vn.parking + FROM parking WHERE code = vParkingCode COLLATE utf8_unicode_ci; IF vParkingFk IS NULL THEN CALL util.throw('parkingNotExist'); - LEAVE proc; END IF; - - IF vParam REGEXP '^[0-9]+$' THEN - -- Se comprueba si es una preparaci贸n previa - SELECT COUNT(*) INTO vIsSaleGroup - FROM vn.saleGroup sg - WHERE sg.id = vParam; - IF vIsSaleGroup THEN - CALL vn.saleGroup_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; + START TRANSACTION; - -- Se comprueba si es un ticket - SELECT COUNT(*) INTO vIsTicket - FROM vn.ticket t - WHERE t.id = vParam - AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + SET vLastWeek = util.VN_CURDATE() - INTERVAL 1 WEEK; - IF vIsTicket THEN - CALL vn.ticket_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Se comprueba si es una coleccion de tickets - SELECT COUNT(*) INTO vIsCollection - FROM vn.collection c - WHERE c.id = vParam - AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsCollection THEN - CALL vn.collection_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; + -- Comprobamos si es una prep. previa, ticket, colecci贸n o shelving + IF (SELECT TRUE FROM saleGroup WHERE id = vParam) THEN + CALL saleGroup_setParking(vParam, vParkingFk); + ELSEIF (SELECT TRUE FROM ticket WHERE id = vParam AND shipped >= vLastWeek) THEN + CALL ticket_setParking(vParam, vParkingFk); + ELSEIF (SELECT TRUE FROM `collection` WHERE id = vParam AND created >= vLastWeek) THEN + CALL collection_setParking(vParam, vParkingFk); + ELSEIF (SELECT TRUE FROM shelving WHERE code = vParam COLLATE utf8_unicode_ci) THEN + CALL shelving_setParking(vParam, vParkingFk); ELSE - -- Por descarte, se considera una matr铆cula - CALL vn.shelving_setParking(vParam, vParkingFk); + CALL util.throw('paramNotExist'); END IF; + + COMMIT; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_DelayTruck.sql b/db/routines/vn/procedures/ticket_DelayTruck.sql index 20601ee49..81896dd8e 100644 --- a/db/routines/vn/procedures/ticket_DelayTruck.sql +++ b/db/routines/vn/procedures/ticket_DelayTruck.sql @@ -3,14 +3,14 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruck`( BEGIN DECLARE done INT DEFAULT FALSE; DECLARE vTicketFk INT; - DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tmp.ticket; + DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tTicket; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; CALL vn.productionControl(vWarehouserFk,0) ; - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket + DROP TEMPORARY TABLE IF EXISTS tTicket; + CREATE TEMPORARY TABLE tTicket SELECT ticketFk FROM tmp.productionBuffer JOIN alertLevel al ON al.code = 'FREE' @@ -31,5 +31,6 @@ BEGIN END LOOP; CLOSE cur1; + DROP TEMPORARY TABLE tTicket, tmp.productionBuffer; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_add.sql b/db/routines/vn/procedures/ticket_add.sql index 5c3c28081..d9b68997c 100644 --- a/db/routines/vn/procedures/ticket_add.sql +++ b/db/routines/vn/procedures/ticket_add.sql @@ -65,6 +65,8 @@ BEGIN IF (vZoneFk IS NULL OR vZoneFk = 0) AND vIsRequiredZone THEN CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); END IF; + + DROP TEMPORARY TABLE tmp.zoneGetShipped; END IF; INSERT INTO ticket ( diff --git a/db/routines/vn/procedures/ticket_checkNoComponents.sql b/db/routines/vn/procedures/ticket_checkNoComponents.sql index 28fe333f0..b03427192 100644 --- a/db/routines/vn/procedures/ticket_checkNoComponents.sql +++ b/db/routines/vn/procedures/ticket_checkNoComponents.sql @@ -20,7 +20,8 @@ BEGIN 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 + JOIN componentType ct ON ct.id = c.typeFk + AND ct.code = 'cost' WHERE t.shipped BETWEEN vShippedFrom AND vShippedTo AND ic.merchandise; diff --git a/db/routines/vn/procedures/ticket_cloneWeekly.sql b/db/routines/vn/procedures/ticket_cloneWeekly.sql index 764e72254..fd45dc9fa 100644 --- a/db/routines/vn/procedures/ticket_cloneWeekly.sql +++ b/db/routines/vn/procedures/ticket_cloneWeekly.sql @@ -213,6 +213,6 @@ BEGIN END; END LOOP; CLOSE rsTicket; - DROP TEMPORARY TABLE IF EXISTS tmp.time; + DROP TEMPORARY TABLE IF EXISTS tmp.time, tmp.zoneGetLanded; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_getFromFloramondo.sql b/db/routines/vn/procedures/ticket_getFromFloramondo.sql index 4d83d6dda..5f2bedbb1 100644 --- a/db/routines/vn/procedures/ticket_getFromFloramondo.sql +++ b/db/routines/vn/procedures/ticket_getFromFloramondo.sql @@ -66,7 +66,7 @@ BEGIN JOIN vn.componentType ct ON ct.id = c.typeFk JOIN vn.sale s ON s.id = sc.saleFk JOIN tmp.ticket t ON t.ticketFk = s.ticketFk - WHERE ct.code = 'FREIGHT' + WHERE ct.code = 'freight' GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk SET tf.freight = sb.freight; @@ -88,7 +88,7 @@ BEGIN -- Margin UPDATE tmp.ticketFloramondo tf - JOIN (SELECT SUM(IF(ct.code = 'COST',sc.value, 0)) cost, + JOIN (SELECT SUM(IF(ct.code = 'cost',sc.value, 0)) cost, SUM(IF(ct.isMargin, sc.value, 0)) margin, t.ticketFk FROM vn.saleComponent sc diff --git a/db/routines/vn/procedures/ticket_setNextState.sql b/db/routines/vn/procedures/ticket_setNextState.sql index d13cd53f0..b09309a47 100644 --- a/db/routines/vn/procedures/ticket_setNextState.sql +++ b/db/routines/vn/procedures/ticket_setNextState.sql @@ -1,14 +1,21 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setNextState`(vSelf INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setNextState`( + vSelf INT +) BEGIN /** - * Cambia el estado del ticket al siguiente estado seg煤n la tabla state + * Cambia el estado del ticket al siguiente estado seg煤n la tabla state. * - * @param vSelf id dle ticket + * @param vSelf Id ticket */ DECLARE vStateFk INT; DECLARE vNewStateFk INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + SELECT stateFk INTO vStateFk FROM ticketState WHERE ticketFk = vSelf; @@ -17,6 +24,10 @@ BEGIN FROM state WHERE id = vStateFk; + IF vNewStateFk IS NULL THEN + CALL util.throw('The ticket not have next state'); + END IF; + INSERT INTO ticketTracking(stateFk, ticketFk, userFk) VALUES (vNewStateFk, vSelf, account.myUser_getId()); END$$ diff --git a/db/routines/vn/procedures/ticket_setParking.sql b/db/routines/vn/procedures/ticket_setParking.sql index 54c64daea..7935e0d60 100644 --- a/db/routines/vn/procedures/ticket_setParking.sql +++ b/db/routines/vn/procedures/ticket_setParking.sql @@ -1,11 +1,14 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setParking`(IN `vTicketFk` VARCHAR(8), IN `vParkingFk` INT) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setParking`( + vSelf INT, + vParkingFk INT +) +BEGIN /** - * Aparca un ticket en un parking + * Aparca un ticket en un parking. * - * @param vTicketFk id del ticket - * @param vParkingFk id del parking + * @param vSelf Id ticket + * @param vParkingFk Id parking */ DECLARE vDone INT DEFAULT FALSE; DECLARE vCollectionTicketFk INT; @@ -14,16 +17,21 @@ proc: BEGIN FROM ticket t LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk - WHERE t.id = vTicketFk; + WHERE t.id = vSelf; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + INSERT INTO vn.ticketParking(ticketFk, parkingFk) SELECT IFNULL(tc2.ticketFk, t.id), vParkingFk FROM ticket t LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk - WHERE t.id = vTicketFk + WHERE t.id = vSelf ON DUPLICATE KEY UPDATE parkingFk = vParkingFk; OPEN vCursor; diff --git a/db/routines/vn/procedures/ticket_setProblem.sql b/db/routines/vn/procedures/ticket_setProblem.sql index bab8f1f52..66d244d5a 100644 --- a/db/routines/vn/procedures/ticket_setProblem.sql +++ b/db/routines/vn/procedures/ticket_setProblem.sql @@ -4,16 +4,34 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setProblem`( ) BEGIN /** - * Update column ticket.problem with a problem code + * Update column ticket.problem with a problem code and SET NULL when + * the problem is not requiered * * @param vProblemCode Code to set or unset - * @table tmp.ticket(ticketFk, hasProblem) + * @table tmp.ticket(ticketFk, hasProblem, isProblemCalcNeeded) */ - UPDATE ticket t - JOIN tmp.ticket tt ON tt.ticketFk = t.id - SET t.problem = CONCAT( - IF(tt.hasProblem, - CONCAT(problem, ',', vProblemCode), - REPLACE(problem, vProblemCode , ''))); + DECLARE vTicketFk INT; + DECLARE vHasProblem INT; + DECLARE vDone BOOL; + DECLARE vTicketList CURSOR FOR SELECT ticketFk, hasProblem FROM tmp.ticket; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vTicketList; + l: LOOP + SET vDone = FALSE; + FETCH vTicketList INTO vTicketFk, vHasProblem; + + IF vDone THEN + LEAVE l; + END IF; + + UPDATE ticket + SET problem = CONCAT( + IF(vHasProblem, + CONCAT(problem, ',', vProblemCode), + REPLACE(problem, vProblemCode , ''))) + WHERE id = vTicketFk; + END LOOP; + CLOSE vTicketList; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/ticket_setProblemFreeze.sql b/db/routines/vn/procedures/ticket_setProblemFreeze.sql index 560bce612..1de939ba7 100644 --- a/db/routines/vn/procedures/ticket_setProblemFreeze.sql +++ b/db/routines/vn/procedures/ticket_setProblemFreeze.sql @@ -9,9 +9,11 @@ BEGIN * @param vClientFk Id Cliente, if NULL all clients */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT t.id ticketFk, FALSE hasProblem + SELECT t.id ticketFk, + FALSE hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t WHERE t.shipped >= util.VN_CURDATE() AND (vClientFk IS NULL OR t.clientFk = vClientFk); @@ -21,7 +23,7 @@ BEGIN JOIN client c ON c.id = ti.clientFk SET t.hasProblem = TRUE WHERE c.isFreezed; - + CALL ticket_setProblem('isFreezed'); DROP TEMPORARY TABLE tmp.ticket; diff --git a/db/routines/vn/procedures/ticket_setProblemRequest.sql b/db/routines/vn/procedures/ticket_setProblemRequest.sql index 19bba5b76..687facfc7 100644 --- a/db/routines/vn/procedures/ticket_setProblemRequest.sql +++ b/db/routines/vn/procedures/ticket_setProblemRequest.sql @@ -9,9 +9,11 @@ BEGIN * @param vSelf Id ticket, if NULL ALL tickets */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT t.id ticketFk, FALSE hasProblem + SELECT t.id ticketFk, + FALSE hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t WHERE t.shipped >= util.VN_CURDATE() AND (vSelf IS NULL OR t.id = vSelf); diff --git a/db/routines/vn/procedures/ticket_setProblemRisk.sql b/db/routines/vn/procedures/ticket_setProblemRisk.sql index 5f73ee838..efa5b10e2 100644 --- a/db/routines/vn/procedures/ticket_setProblemRisk.sql +++ b/db/routines/vn/procedures/ticket_setProblemRisk.sql @@ -10,21 +10,30 @@ BEGIN */ DECLARE vHasRisk BOOL; DECLARE vHasHighRisk BOOL; + DECLARE vIsProblemCalcNeeded BOOL; - SELECT t.risk > (c.credit + 10), ((t.risk - cc.riskTolerance) > (c.credit + 10)) - INTO vHasRisk, vHasHighRisk + SELECT t.risk > (c.credit + 10), + (t.risk - cc.riskTolerance) > (c.credit + 10), + ticket_isProblemCalcNeeded(t.id) + INTO vHasRisk, vHasHighRisk, vIsProblemCalcNeeded FROM client c JOIN ticket t ON t.clientFk = c.id JOIN clientConfig cc WHERE t.id = vSelf; CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - SELECT vSelf ticketFk, vHasRisk hasProblem; + ENGINE = MEMORY + SELECT vSelf ticketFk, + vHasRisk hasProblem, + vIsProblemCalcNeeded isProblemCalcNeeded; CALL ticket_setProblem('hasRisk'); CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - SELECT vSelf ticketFk, vHasHighRisk hasProblem; + ENGINE = MEMORY + SELECT vSelf ticketFk, + vHasHighRisk hasProblem, + vIsProblemCalcNeeded isProblemCalcNeeded; CALL ticket_setProblem('hasHighRisk'); diff --git a/db/routines/vn/procedures/ticket_setProblemRounding.sql b/db/routines/vn/procedures/ticket_setProblemRounding.sql index 81294325c..fb580eacf 100644 --- a/db/routines/vn/procedures/ticket_setProblemRounding.sql +++ b/db/routines/vn/procedures/ticket_setProblemRounding.sql @@ -18,8 +18,11 @@ BEGIN CALL buyUltimate(vWarehouseFk, vDated); - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - SELECT s.id saleFk , MOD(s.quantity, b.`grouping`) hasProblem + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk, isProblemCalcNeeded)) + SELECT s.id saleFk , + MOD(s.quantity, b.`grouping`) hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk diff --git a/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql b/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql index 00918426b..9877b5acc 100644 --- a/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql +++ b/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql @@ -9,9 +9,11 @@ BEGIN * @param vClientFk Id cliente, if NULL all clients */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT t.id ticketFk, IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem + SELECT t.id ticketFk, + IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t JOIN client c ON c.id = t.clientFk WHERE t.shipped >= util.VN_CURDATE() diff --git a/db/routines/vn/procedures/ticket_setProblemTooLittle.sql b/db/routines/vn/procedures/ticket_setProblemTooLittle.sql index 98a0787af..48cc47809 100644 --- a/db/routines/vn/procedures/ticket_setProblemTooLittle.sql +++ b/db/routines/vn/procedures/ticket_setProblemTooLittle.sql @@ -8,13 +8,17 @@ BEGIN * * @param vSelf Id del ticket */ + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT vSelf ticketFk, ticket_isTooLittle(vSelf) hasProblem; + SELECT vSelf ticketFk, + ticket_isTooLittle(vSelf) hasProblem, + ticket_isProblemCalcNeeded(vSelf) isProblemCalcNeeded; CALL ticket_setProblem('isTooLittle'); DROP TEMPORARY TABLE tmp.ticket; + END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql b/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql index cd1f42783..1f41c0716 100644 --- a/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql +++ b/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql @@ -10,7 +10,7 @@ BEGIN * @param vItemFk Id del item, NULL ALL items */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY WITH tickets AS( SELECT t.id ticketFk @@ -19,7 +19,9 @@ BEGIN WHERE t.shipped >= util.VN_CURDATE() AND (s.itemFk = vItemFk OR vItemFk IS NULL) GROUP BY t.id - )SELECT ticketFk, ticket_isTooLittle(ticketFk) hasProblem + )SELECT ticketFk, + ticket_isTooLittle(ticketFk) hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM tickets; CALL ticket_setProblem('isTooLittle'); diff --git a/db/routines/vn/procedures/ticket_setRisk.sql b/db/routines/vn/procedures/ticket_setRisk.sql index f5e6cb5a0..32f3647b7 100644 --- a/db/routines/vn/procedures/ticket_setRisk.sql +++ b/db/routines/vn/procedures/ticket_setRisk.sql @@ -8,6 +8,7 @@ BEGIN * @param vClientFk Id cliente */ DECLARE vHasDebt BOOL; + DECLARE vStarted DATETIME; SELECT COUNT(*) INTO vHasDebt FROM `client` @@ -16,22 +17,24 @@ BEGIN IF vHasDebt THEN + SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted + FROM clientConfig; + CREATE OR REPLACE TEMPORARY TABLE tTicketRisk (KEY (ticketFk)) ENGINE = MEMORY WITH ticket AS( - SELECT id ticketFk, companyFk, DATE(shipped) dated - FROM vn.ticket t + SELECT id ticketFk, + companyFk, + DATE(shipped) dated, + totalWithVat, + ticket_isProblemCalcNeeded(id) isProblemCalcNeeded + FROM vn.ticket WHERE clientFk = vClientFk AND refFk IS NULL AND NOT isDeleted - AND totalWithoutVat <> 0 - ), dated AS( - SELECT t.companyFk, MIN(DATE(t.dated) - INTERVAL cc.riskScope MONTH) started, - MAX(DATE(t.dated)) ended - FROM ticket t - JOIN vn.clientConfig cc - GROUP BY t.companyFk + AND IFNULL(totalWithVat, 0) <> 0 + AND shipped > vStarted ), balance AS( SELECT SUM(amount)amount, companyFk FROM ( @@ -49,15 +52,11 @@ BEGIN WHERE companyFk GROUP BY companyFk ), uninvoiced AS( - SELECT t.companyFk, DATE(t.shipped) dated, SUM(IFNULL(t.totalWithVat, 0)) amount - FROM vn.ticket t - JOIN dated d - WHERE t.clientFk = vClientFk - AND t.refFk IS NULL - AND t.shipped BETWEEN d.started AND d.ended - GROUP BY t.companyFk, DATE(t.shipped) + SELECT companyFk, dated, SUM(totalWithVat) amount + FROM ticket + GROUP BY companyFk, dated ), receipt AS( - SELECT companyFk,DATE(payed) dated, SUM(amountPaid) amount + SELECT companyFk, DATE(payed) dated, SUM(amountPaid) amount FROM vn.receipt WHERE clientFk = vClientFk AND payed > util.VN_CURDATE() @@ -79,7 +78,15 @@ BEGIN UPDATE ticket t JOIN tTicketRisk tr ON tr.ticketFk = t.id - SET t.risk = tr.amount; + SET t.risk = tr.amount + WHERE tr.isProblemCalcNeeded + ORDER BY t.id; + + UPDATE ticket t + JOIN tTicketRisk tr ON tr.ticketFk = t.id + SET t.risk = NULL + WHERE tr.isProblemCalcNeeded + ORDER BY t.id; DROP TEMPORARY TABLE tTicketRisk; END IF; diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index e2c55e28a..c2ec50fd9 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -1,15 +1,15 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_splitItemPackingType`( - vTicketFk INT, - vOriginalItemPackingTypeFk VARCHAR(1) + vSelf INT, + vItemPackingTypeFk VARCHAR(1) ) BEGIN /** * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. * Respeta el id inicial para el tipo propuesto. * - * @param vTicketFk Identificador de vn.ticket - * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el n煤mero de ticket original + * @param vSelf Id ticket + * @param vItemPackingTypeFk Tipo para el que se reserva el n煤mero de ticket original * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; @@ -19,11 +19,11 @@ BEGIN DECLARE vErrorNumber INT; DECLARE vErrorMsg TEXT; - DECLARE cur1 CURSOR FOR + DECLARE vSaleGroup CURSOR FOR SELECT itemPackingTypeFk - FROM tmp.saleGroup + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL - ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC; + ORDER BY (itemPackingTypeFk = vItemPackingTypeFk) DESC; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -36,35 +36,44 @@ BEGIN CALL util.debugAdd('ticket_splitItemPackingType', JSON_OBJECT( 'errorNumber', vErrorNumber, 'errorMsg', vErrorMsg, - 'ticketFk', vTicketFk + 'ticketFk', vSelf )); -- Tmp + ROLLBACK; RESIGNAL; END; - DELETE FROM vn.sale - WHERE quantity = 0 - AND ticketFk = vTicketFk; + START TRANSACTION; - CREATE OR REPLACE TEMPORARY TABLE tmp.sale + SELECT id + FROM sale + WHERE ticketFk = vSelf + AND NOT quantity + FOR UPDATE; + + DELETE FROM sale + WHERE NOT quantity + AND ticketFk = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tSale (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT s.id, i.itemPackingTypeFk , IFNULL(sv.litros, 0) litros - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id - WHERE s.ticketFk = vTicketFk; + SELECT s.id, i.itemPackingTypeFk, IFNULL(sv.litros, 0) litros + FROM sale s + JOIN item i ON i.id = s.itemFk + LEFT JOIN saleVolume sv ON sv.saleFk = s.id + WHERE s.ticketFk = vSelf; - CREATE OR REPLACE TEMPORARY TABLE tmp.saleGroup + CREATE OR REPLACE TEMPORARY TABLE tSaleGroup ENGINE = MEMORY SELECT itemPackingTypeFk, SUM(litros) totalLitros - FROM tmp.sale + FROM tSale GROUP BY itemPackingTypeFk; SELECT COUNT(*) INTO vPackingTypesToSplit - FROM tmp.saleGroup + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT ( + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( ticketFk INT, itemPackingTypeFk VARCHAR(1) ) ENGINE = MEMORY; @@ -72,55 +81,63 @@ BEGIN CASE vPackingTypesToSplit WHEN 0 THEN INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vTicketFk, vItemPackingTypeFk); + VALUES(vSelf, vItemPackingTypeFk); WHEN 1 THEN INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - SELECT vTicketFk, itemPackingTypeFk - FROM tmp.saleGroup + SELECT vSelf, itemPackingTypeFk + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; ELSE - OPEN cur1; - - FETCH cur1 INTO vItemPackingTypeFk; + OPEN vSaleGroup; + FETCH vSaleGroup INTO vItemPackingTypeFk; INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vTicketFk, vItemPackingTypeFk); + VALUES(vSelf, vItemPackingTypeFk); - read_loop: LOOP - FETCH cur1 INTO vItemPackingTypeFk; + l: LOOP + SET vDone = FALSE; + FETCH vSaleGroup INTO vItemPackingTypeFk; IF vDone THEN - LEAVE read_loop; + LEAVE l; END IF; - CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); + CALL ticket_Clone(vSelf, vNewTicketFk); INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) VALUES(vNewTicketFk, vItemPackingTypeFk); END LOOP; - CLOSE cur1; + CLOSE vSaleGroup; - UPDATE vn.sale s - JOIN tmp.sale ts ON ts.id = s.id + SELECT s.id + FROM sale s + JOIN tSale ts ON ts.id = s.id + JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + FOR UPDATE; + + UPDATE sale s + JOIN tSale ts ON ts.id = s.id JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk SET s.ticketFk = t.ticketFk; SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM tmp.saleGroup sg + FROM tSaleGroup sg WHERE sg.itemPackingTypeFk IS NOT NULL ORDER BY sg.itemPackingTypeFk LIMIT 1; - UPDATE vn.sale s - JOIN tmp.sale ts ON ts.id = s.id + UPDATE sale s + JOIN tSale ts ON ts.id = s.id JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk SET s.ticketFk = t.ticketFk WHERE ts.itemPackingTypeFk IS NULL; END CASE; + COMMIT; + DROP TEMPORARY TABLE - tmp.sale, - tmp.saleGroup; + tSale, + tSaleGroup; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/workerTimeControl_direction.sql b/db/routines/vn/procedures/workerTimeControl_direction.sql index f7a68e1e4..8e807084c 100644 --- a/db/routines/vn/procedures/workerTimeControl_direction.sql +++ b/db/routines/vn/procedures/workerTimeControl_direction.sql @@ -9,6 +9,8 @@ BEGIN */ DECLARE vLastIn DATETIME ; DECLARE vIsMiddleOdd BOOLEAN ; + DECLARE vMailTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; IF (vTimed IS NULL) THEN SET vTimed = util.VN_NOW(); @@ -57,5 +59,18 @@ BEGIN VALUES('in', NULL); END IF; + IF (SELECT option1 IS NULL AND option2 IS NULL FROM tmp.workerTimeControlDirection) THEN + SELECT CONCAT(u.name, '@verdnatura.es'), CONCAT(w.firstName, ' ', w.lastName) + INTO vMailTo, vUserName + FROM account.user u + JOIN worker w ON w.bossFk = u.id + WHERE w.id = vWorkerFk; + + CALL mail_insert( + vMailTo, + vMailTo, + 'Error al fichar', + CONCAT(vUserName, ' tiene problemas para fichar')); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/zone_getCollisions.sql b/db/routines/vn/procedures/zone_getCollisions.sql index 023b9aac2..e28b2b341 100644 --- a/db/routines/vn/procedures/zone_getCollisions.sql +++ b/db/routines/vn/procedures/zone_getCollisions.sql @@ -103,6 +103,7 @@ BEGIN DROP TEMPORARY TABLE geoCollision, tmp.zone, - tmp.zoneNodes; + tmp.zoneNodes, + tmp.zoneOption; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/delivery_beforeInsert.sql b/db/routines/vn/triggers/delivery_beforeInsert.sql index 89431c30f..eb4a6f21a 100644 --- a/db/routines/vn/triggers/delivery_beforeInsert.sql +++ b/db/routines/vn/triggers/delivery_beforeInsert.sql @@ -3,18 +3,11 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeInsert BEFORE INSERT ON `delivery` FOR EACH ROW BEGIN - - IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL) + IF (NEW.longitude IS NOT NULL + AND NEW.latitude IS NOT NULL + AND NEW.ticketFK IS NOT NULL) THEN - UPDATE address - SET longitude = NEW.longitude, - latitude = NEW.latitude - WHERE id IN ( - SELECT addressFK - FROM ticket - WHERE id = NEW.ticketFk - ); + CALL address_updateCoordinates(NEW.ticketFk, NEW.longitude, NEW.latitude); END IF; - END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/delivery_beforeUpdate.sql b/db/routines/vn/triggers/delivery_beforeUpdate.sql index 7e6aa7d4c..6206d4722 100644 --- a/db/routines/vn/triggers/delivery_beforeUpdate.sql +++ b/db/routines/vn/triggers/delivery_beforeUpdate.sql @@ -3,18 +3,11 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeUpdate BEFORE UPDATE ON `delivery` FOR EACH ROW BEGIN - -IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL) + IF (NEW.longitude IS NOT NULL + AND NEW.latitude IS NOT NULL + AND NEW.ticketFK IS NOT NULL) THEN - UPDATE address - SET longitude = NEW.longitude, - latitude = NEW.latitude - WHERE id IN ( - SELECT addressFK - FROM ticket - WHERE id = NEW.ticketFk - ); + CALL address_updateCoordinates(NEW.ticketFk, NEW.longitude, NEW.latitude); END IF; - END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/itemMinimumQuantity_afterDelete.sql b/db/routines/vn/triggers/itemMinimumQuantity_afterDelete.sql new file mode 100644 index 000000000..1da5a5942 --- /dev/null +++ b/db/routines/vn/triggers/itemMinimumQuantity_afterDelete.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemMinimumQuantity_afterDelete` + AFTER DELETE ON `itemMinimumQuantity` + FOR EACH ROW +BEGIN + INSERT INTO itemLog + SET `action` = 'delete', + `changedModel` = 'ItemMinimumQuantity', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/itemMinimumQuantity_beforeInsert.sql b/db/routines/vn/triggers/itemMinimumQuantity_beforeInsert.sql new file mode 100644 index 000000000..8833ac968 --- /dev/null +++ b/db/routines/vn/triggers/itemMinimumQuantity_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemMinimumQuantity_beforeInsert` + BEFORE INSERT ON `itemMinimumQuantity` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/itemMinimumQuantity_beforeUpdate.sql b/db/routines/vn/triggers/itemMinimumQuantity_beforeUpdate.sql new file mode 100644 index 000000000..ef030f9f9 --- /dev/null +++ b/db/routines/vn/triggers/itemMinimumQuantity_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemMinimumQuantity_beforeUpdate` + BEFORE UPDATE ON `itemMinimumQuantity` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/itemShelving _afterDelete.sql b/db/routines/vn/triggers/itemShelving _afterDelete.sql index 7c0d54358..9a1759eff 100644 --- a/db/routines/vn/triggers/itemShelving _afterDelete.sql +++ b/db/routines/vn/triggers/itemShelving _afterDelete.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving _afterDelete` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterDelete` AFTER DELETE ON `itemShelving` FOR EACH ROW BEGIN diff --git a/db/routines/vn/triggers/productionConfig_afterDelete.sql b/db/routines/vn/triggers/productionConfig_afterDelete.sql new file mode 100644 index 000000000..384bf681e --- /dev/null +++ b/db/routines/vn/triggers/productionConfig_afterDelete.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`productionConfig_afterDelete` + AFTER DELETE ON `productionConfig` + FOR EACH ROW +BEGIN + INSERT INTO productionConfig + SET `action` = 'delete', + `changedModel` = 'ProductionConfig', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/productionConfig_beforeInsert.sql b/db/routines/vn/triggers/productionConfig_beforeInsert.sql new file mode 100644 index 000000000..99b217be4 --- /dev/null +++ b/db/routines/vn/triggers/productionConfig_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`productionConfig_beforeInsert` + BEFORE INSERT ON `productionConfig` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/productionConfig_beforeUpdate.sql b/db/routines/vn/triggers/productionConfig_beforeUpdate.sql new file mode 100644 index 000000000..f1ceaa471 --- /dev/null +++ b/db/routines/vn/triggers/productionConfig_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`productionConfig_beforeUpdate` + BEFORE UPDATE ON `productionConfig` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/views/saleCost.sql b/db/routines/vn/views/saleCost.sql index 27265aa93..304b9e3a3 100644 --- a/db/routines/vn/views/saleCost.sql +++ b/db/routines/vn/views/saleCost.sql @@ -19,4 +19,4 @@ FROM ( ) JOIN `vn`.`componentType` `ct` ON(`ct`.`id` = `c`.`typeFk`) ) -WHERE `ct`.`type` = 'coste' +WHERE `ct`.`code` = 'cost' diff --git a/db/routines/vn/views/sale_freightComponent.sql b/db/routines/vn/views/sale_freightComponent.sql index 7a329e0ee..269a8cca1 100644 --- a/db/routines/vn/views/sale_freightComponent.sql +++ b/db/routines/vn/views/sale_freightComponent.sql @@ -16,6 +16,6 @@ FROM ( ) JOIN `vn`.`componentType` `ct` ON( `ct`.`id` = `c`.`typeFk` - AND `ct`.`type` = 'agencia' + AND `ct`.`code` = 'freight' ) ) diff --git a/db/routines/vn2008/views/Tipos.sql b/db/routines/vn2008/views/Tipos.sql index 4cde954f1..5b96c1766 100644 --- a/db/routines/vn2008/views/Tipos.sql +++ b/db/routines/vn2008/views/Tipos.sql @@ -9,14 +9,9 @@ AS SELECT `it`.`id` AS `tipo_id`, `it`.`workerFk` AS `Id_Trabajador`, `it`.`life` AS `life`, `it`.`isPackaging` AS `isPackaging`, - `it`.`density` AS `density`, `it`.`isInventory` AS `inventory`, `it`.`created` AS `odbc_date`, `it`.`making` AS `confeccion`, `it`.`temperatureFk` AS `Temperatura`, - `it`.`promo` AS `promo`, - `it`.`maneuver` AS `maneuver`, - `it`.`target` AS `target`, - `it`.`topMargin` AS `top_margin`, - `it`.`profit` AS `profit` + `it`.`promo` AS `promo` FROM `vn`.`itemType` `it` diff --git a/db/routines/vn2008/views/buySource.sql b/db/routines/vn2008/views/buySource.sql index 33226a1dc..850483833 100644 --- a/db/routines/vn2008/views/buySource.sql +++ b/db/routines/vn2008/views/buySource.sql @@ -54,8 +54,7 @@ AS SELECT `b`.`entryFk` AS `Id_Entrada`, `i`.`packingOut` AS `packingOut`, `b`.`itemOriginalFk` AS `itemOriginalFk`, `io`.`longName` AS `itemOriginalName`, - `it`.`gramsMax` AS `gramsMax`, - `i`.`minQuantity` AS `minQuantity` + `it`.`gramsMax` AS `gramsMax` FROM ( ( ( diff --git a/db/routines/vn2008/views/buy_edi.sql b/db/routines/vn2008/views/buy_edi.sql index 0d194c89e..d00196e95 100644 --- a/db/routines/vn2008/views/buy_edi.sql +++ b/db/routines/vn2008/views/buy_edi.sql @@ -2,7 +2,6 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vn2008`.`buy_edi` AS SELECT `t`.`id` AS `id`, - `t`.`barcode` AS `barcode`, `t`.`entryYear` AS `entry_year`, `t`.`deliveryNumber` AS `delivery_number`, `t`.`fec` AS `fec`, diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql new file mode 100644 index 000000000..c53a09549 --- /dev/null +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -0,0 +1,23 @@ +-- Place your SQL code here +CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( + `agencyModeFk` int(11) NOT NULL, + PRIMARY KEY (`agencyModeFk`) +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci COMMENT='Agencias de entrada de mercancias'; + +INSERT IGNORE INTO vn.agencyIncoming (agencyModeFk) VALUES +(1343), (1002), (1282), (841), (1303), (714), (556), (1786), (1785), (1784), +(1780), (1783), (1758), (1782), (1772), (1789), (1776), (1791), (1778), (1792), +(1779), (1362), (681), (1765), (15), (1594), (1706), (1707), (907), (1260), +(1715), (1371), (1372), (53), (689), (1375), (738), (742), (1307), (1700), (608), +(1311), (1315), (1339), (1433), (1338), (1332), (1844), (842), (1382), (1466), +(1719), (1723), (1725), (1720), (1732), (1736), (1728), (1724), (1726), (1727), +(1767), (1734), (1730), (1845), (1729), (1746), (1699), (2), (671), (1379), (614), +(1718), (1697), (62), (1529), (1392), (1378), (1438), (1796), (1688), (686), +(1326), (1691), (1), (1560), (1695), (1696), (1558), (1648), (1649), (1598), +(1680), (1694), (1600), (1601), (1602), (1712), (1603), (1604), (1641), (1692), +(1693), (1650), (1683), (1682), (1681), (1713), (1826), (1768), (1769), (1770), +(1593), (1443), (1244), (1679), (1006), (1361), (1102), (1655), (1744), (1225), +(1007); diff --git a/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql b/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql new file mode 100644 index 000000000..288785191 --- /dev/null +++ b/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql @@ -0,0 +1,22 @@ +ALTER TABLE vn.claimLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.clientLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.deviceProductionLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.entryLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.invoiceInLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.itemLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.packingSiteDeviceLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.parkingLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.rateLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.routeLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.shelvingLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.supplierLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.ticketLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.travelLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.userLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.workerLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.zoneLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); + +ALTER TABLE account.userLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE account.signInLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE account.roleLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE account.accountLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); \ No newline at end of file diff --git a/db/versions/11081-wheatRaphis/00-firstScript.sql b/db/versions/11081-wheatRaphis/00-firstScript.sql index 2e4424c5a..70bbaabdb 100644 --- a/db/versions/11081-wheatRaphis/00-firstScript.sql +++ b/db/versions/11081-wheatRaphis/00-firstScript.sql @@ -1,8 +1,8 @@ --- Place your SQL code here - -USE vn; - -ALTER TABLE vn.roadmap ADD kmStart mediumint(9) DEFAULT NULL NULL; -ALTER TABLE vn.roadmap ADD kmEnd mediumint(9) DEFAULT NULL NULL; -ALTER TABLE vn.roadmap ADD started DATETIME NULL; -ALTER TABLE vn.roadmap ADD finished DATETIME NULL; +-- Place your SQL code here + +USE vn; + +ALTER TABLE vn.roadmap ADD kmStart mediumint(9) DEFAULT NULL NULL; +ALTER TABLE vn.roadmap ADD kmEnd mediumint(9) DEFAULT NULL NULL; +ALTER TABLE vn.roadmap ADD started DATETIME NULL; +ALTER TABLE vn.roadmap ADD finished DATETIME NULL; diff --git a/db/versions/11118-limeCymbidium/00-firstScript.sql b/db/versions/11118-limeCymbidium/00-firstScript.sql new file mode 100644 index 000000000..3921a8a13 --- /dev/null +++ b/db/versions/11118-limeCymbidium/00-firstScript.sql @@ -0,0 +1,21 @@ + +INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) + VALUES ('Entry','filter','READ','ALLOW','ROLE','supplier'); + +INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) + VALUES ('Entry','getBuys','READ','ALLOW','ROLE','supplier'); + +INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) + VALUES ('Entry','buyLabel','READ','ALLOW','ROLE','supplier'); + +INSERT IGNORE INTO `account`.`role` (`name`,`description`,`hasLogin`,`created`,`modified`) + VALUES ('supplier','Proveedores',1,'2017-10-10 14:58:58.000','2017-10-10 14:59:20.000'); +SET @supplierFk =LAST_INSERT_ID(); +INSERT IGNORE INTO account.roleInherit (`role`,`inheritsFrom`) + VALUES (@supplierFk,2); + +UPDATE salix.ACL + SET principalId='$authenticated' + WHERE id=264; + + diff --git a/db/versions/11119-tealGerbera/00-firstScript.sql b/db/versions/11119-tealGerbera/00-firstScript.sql new file mode 100644 index 000000000..40b3b0424 --- /dev/null +++ b/db/versions/11119-tealGerbera/00-firstScript.sql @@ -0,0 +1,9 @@ +ALTER TABLE vn.componentType + CHANGE code code varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL AFTER id; +ALTER TABLE vn.componentType + CHANGE `type` name varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL; +UPDATE IGNORE vn.componentType + SET code = LOWER(code); +UPDATE IGNORE vn.componentType + SET code = 'other' + WHERE id = 12; \ No newline at end of file diff --git a/db/versions/11120-brownTulip/00-firstScript.sql b/db/versions/11120-brownTulip/00-firstScript.sql new file mode 100644 index 000000000..c4ded80bb --- /dev/null +++ b/db/versions/11120-brownTulip/00-firstScript.sql @@ -0,0 +1,6 @@ +ALTER TABLE vn.itemType + CHANGE maneuver maneuver__ double DEFAULT 0.21 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE target target__ double DEFAULT 0.15 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE topMargin topMargin__ double DEFAULT 0.3 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE profit profit__ double DEFAULT 0.02 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE density density__ double DEFAULT 167 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418 Almacena el valor por defecto de la densidad en kg/m3 para el calculo de los portes aereos, en articulos se guarda la correcta'; \ No newline at end of file diff --git a/db/versions/11121-silverAralia/00-firstScript.sql b/db/versions/11121-silverAralia/00-firstScript.sql new file mode 100644 index 000000000..20b0e8195 --- /dev/null +++ b/db/versions/11121-silverAralia/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE account.mailAliasAccount + ADD editorFk INT(10) UNSIGNED DEFAULT NULL, + ADD CONSTRAINT mailAliasAccount_editorFk FOREIGN KEY (editorFk) + REFERENCES account.`user`(id); \ No newline at end of file diff --git a/db/versions/11126-blueCamellia/00-firstScript.sql b/db/versions/11126-blueCamellia/00-firstScript.sql new file mode 100644 index 000000000..40c5e2b37 --- /dev/null +++ b/db/versions/11126-blueCamellia/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE `vn`.`client` +ADD COLUMN `hasDailyInvoice` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el cliente requiere facturaci贸n diaria por defecto se copiar谩 lo que tenga country.hasDailyInvoice'; diff --git a/db/versions/11128-turquoiseCymbidium/00-firstScript.sql b/db/versions/11128-turquoiseCymbidium/00-firstScript.sql new file mode 100644 index 000000000..4f6cafcf8 --- /dev/null +++ b/db/versions/11128-turquoiseCymbidium/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.calendar ADD created timestamp DEFAULT current_timestamp() NOT NULL AFTER dated; diff --git a/db/versions/11129-limeHydrangea/00-firstScript.sql b/db/versions/11129-limeHydrangea/00-firstScript.sql new file mode 100644 index 000000000..eb2320ee1 --- /dev/null +++ b/db/versions/11129-limeHydrangea/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.greuge CHANGE Id id int(10) unsigned auto_increment NOT NULL; diff --git a/db/versions/11130-crimsonIvy/00-firstScript.sql b/db/versions/11130-crimsonIvy/00-firstScript.sql new file mode 100644 index 000000000..c93f2f6b7 --- /dev/null +++ b/db/versions/11130-crimsonIvy/00-firstScript.sql @@ -0,0 +1,23 @@ +ALTER TABLE vn.productionConfig + ADD editorFk int(10) unsigned DEFAULT NULL NULL; +ALTER TABLE vn.productionConfig + ADD CONSTRAINT productionConfig_user_FK FOREIGN KEY (editorFk) REFERENCES account.`user`(id); + +CREATE OR REPLACE TABLE `vn`.`productionConfigLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(11) DEFAULT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete','select') NOT NULL, + `creationDate` timestamp NULL DEFAULT current_timestamp(), + `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, + `changedModel` enum('ProductionConfig') NOT NULL DEFAULT 'ProductionConfig', + `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)), + `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)), + `changedModelId` int(11) NOT NULL, + `changedModelValue` varchar(45) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `productionConfigLog_userFk` (`userFk`), + KEY `productionConfigLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`), + KEY `productionConfigLog_originFk` (`originFk`,`creationDate`), + CONSTRAINT `productionConfigUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; diff --git a/db/versions/11131-brownPhormium/00-firstScript.sql b/db/versions/11131-brownPhormium/00-firstScript.sql new file mode 100644 index 000000000..341c9f1a3 --- /dev/null +++ b/db/versions/11131-brownPhormium/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.itemShelving ADD isSplit tinyint(1) NULL COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda'; \ No newline at end of file diff --git a/db/versions/11132-aquaDracena/00-firstScript.vn.sql b/db/versions/11132-aquaDracena/00-firstScript.vn.sql new file mode 100644 index 000000000..64f8442b4 --- /dev/null +++ b/db/versions/11132-aquaDracena/00-firstScript.vn.sql @@ -0,0 +1,2 @@ +INSERT IGNORE INTO vn.observationType (`description`,code) + VALUES ('Sustituci贸n','substitution'); diff --git a/db/versions/11135-whiteErica/00-firstScript.sql b/db/versions/11135-whiteErica/00-firstScript.sql new file mode 100644 index 000000000..902608a3e --- /dev/null +++ b/db/versions/11135-whiteErica/00-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX travel_landed_IDX USING BTREE ON vn.travel (landed DESC,warehouseInFk,warehouseOutFk); diff --git a/db/versions/11136-maroonMedeola/00-firstScript.sql b/db/versions/11136-maroonMedeola/00-firstScript.sql new file mode 100644 index 000000000..b0b92c7e9 --- /dev/null +++ b/db/versions/11136-maroonMedeola/00-firstScript.sql @@ -0,0 +1,6 @@ +RENAME TABLE vn.addressShortage TO vn.addressWaste; +ALTER TABLE vn.addressWaste ADD `type` ENUM('internal', 'external') NOT NULL; +INSERT IGNORE INTO vn.addressWaste (addressFk,`type`) VALUES + (2230,'external'), + (5986,'external'), + (7475,'external'); diff --git a/db/versions/11137-salmonRoebelini/00-firstScript.sql b/db/versions/11137-salmonRoebelini/00-firstScript.sql new file mode 100644 index 000000000..69d20ac6d --- /dev/null +++ b/db/versions/11137-salmonRoebelini/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.expeditionState + MODIFY COLUMN userFk INT(10) UNSIGNED, + ADD CONSTRAINT expeditionState_userFk FOREIGN KEY (userFk) + REFERENCES account.`user`(id); \ No newline at end of file diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql new file mode 100644 index 000000000..d492e6470 --- /dev/null +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -0,0 +1,8 @@ +ALTER TABLE `vn`.`claimDestination` +ADD COLUMN `code` varchar(45) DEFAULT NULL; + +UPDATE IGNORE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; +UPDATE IGNORE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; +UPDATE IGNORE vn.claimDestination SET code='Manufacturing' WHERE description = 'Confeccion'; +UPDATE IGNORE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; +UPDATE IGNORE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file diff --git a/db/versions/11140-azurePhormium/00-firstScript.sql b/db/versions/11140-azurePhormium/00-firstScript.sql new file mode 100644 index 000000000..7c89110bb --- /dev/null +++ b/db/versions/11140-azurePhormium/00-firstScript.sql @@ -0,0 +1,3 @@ +ALTER TABLE vn.vehicle DROP FOREIGN KEY provinceFk; +ALTER TABLE vn.vehicle + ADD CONSTRAINT vehicle_warehouse_FK FOREIGN KEY (warehouseFk) REFERENCES vn.warehouse(id) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/db/versions/11149-silverSalal/00-firstScript.sql b/db/versions/11149-silverSalal/00-firstScript.sql new file mode 100644 index 000000000..e642dd2e4 --- /dev/null +++ b/db/versions/11149-silverSalal/00-firstScript.sql @@ -0,0 +1,30 @@ +ALTER TABLE vn.item CHANGE minQuantity minQuantity__ int(10) unsigned DEFAULT + NULL NULL COMMENT '@deprecated 2024-07-11 refs #7704 Cantidad m铆nima para una l铆nea de venta'; + +CREATE TABLE `vn`.`itemMinimumQuantity` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(10) NOT NULL, + `quantity` int(10) NOT NULL, + `started` date NOT NULL, + `ended` date DEFAULT NULL, + `warehouseFk` smallint(5) unsigned DEFAULT NULL, + `created` timestamp NOT NULL DEFAULT current_timestamp(), + `editorFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `itemMinimumQuantity_UNIQUE` (`itemFk`, `started`, `ended`, `warehouseFk`), + KEY `itemFk` (`itemFk`), + KEY `started` (`started`), + KEY `ended` (`ended`), + KEY `warehouseFk` (`warehouseFk`), + KEY `editorFk` (`editorFk`), + CONSTRAINT `itemMinimumQuantity_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemMinimumQuantity_ibfk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `itemMinimumQuantity_ibfk_3` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), + CONSTRAINT `itemMinimumQuantity_check_1` CHECK (`started` <= `ended`) +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +GRANT SELECT, UPDATE, DELETE, INSERT ON TABLE vn.itemMinimumQuantity TO buyer; +GRANT EXECUTE ON PROCEDURE vn.ticketCalculatePurge TO guest; + +ALTER TABLE vn.itemLog MODIFY COLUMN changedModel enum('Item','ItemBarcode','ItemBotanical','ItemNiche','ItemTag','ItemTaxCountry','ItemMinimumQuantity') + CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT 'Item' NOT NULL; diff --git a/db/versions/11150-bronzeEucalyptus/00-firstScript.sql b/db/versions/11150-bronzeEucalyptus/00-firstScript.sql new file mode 100644 index 000000000..c9a619618 --- /dev/null +++ b/db/versions/11150-bronzeEucalyptus/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.itemMinimumQuantity + ADD CONSTRAINT itemMinimumQuantity_check CHECK (quantity > 0); diff --git a/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js b/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js index 5c8eba571..ad0975889 100644 --- a/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js +++ b/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js @@ -57,7 +57,7 @@ describe('Ticket List sale path', () => { let searchValue = 'Melee weapon heavy shield 100cm'; await page.autocompleteSearch(selectors.ticketSales.secondSaleIdAutocomplete, searchValue); await page.waitToClick(selectors.ticketSales.secondSaleQuantityCell); - await page.type(selectors.ticketSales.secondSaleQuantity, '1'); + await page.type(selectors.ticketSales.secondSaleQuantity, '8'); await page.keyboard.press('Enter'); const message = await page.waitForSnackbar(); diff --git a/loopback/common/methods/application/spec/execute.spec.js b/loopback/common/methods/application/spec/execute.spec.js index 1a0a8ace9..ca4efd9cc 100644 --- a/loopback/common/methods/application/spec/execute.spec.js +++ b/loopback/common/methods/application/spec/execute.spec.js @@ -2,18 +2,9 @@ const models = require('vn-loopback/server/server').models; describe('Application execute()/executeProc()/executeFunc()', () => { const userWithoutPrivileges = 1; - const userWithPrivileges = 9; const userWithInheritedPrivileges = 120; let tx; - - function getCtx(userId) { - return { - req: { - accessToken: {userId}, - headers: {origin: 'http://localhost'} - } - }; - } + const ctx = beforeAll.getCtx(); beforeEach(async() => { tx = await models.Application.beginTransaction({}); @@ -42,7 +33,7 @@ describe('Application execute()/executeProc()/executeFunc()', () => { }); it('should throw error when execute procedure and not have privileges', async() => { - const ctx = getCtx(userWithoutPrivileges); + const ctx = {req: {accessToken: {userId: userWithoutPrivileges}}}; let error; try { @@ -66,7 +57,6 @@ describe('Application execute()/executeProc()/executeFunc()', () => { }); it('should execute procedure and get data', async() => { - const ctx = getCtx(userWithPrivileges); try { const options = {transaction: tx}; @@ -90,7 +80,6 @@ describe('Application execute()/executeProc()/executeFunc()', () => { describe('Application executeProc()', () => { it('should execute procedure and get data (executeProc)', async() => { - const ctx = getCtx(userWithPrivileges); try { const options = {transaction: tx}; @@ -115,7 +104,6 @@ describe('Application execute()/executeProc()/executeFunc()', () => { describe('Application executeFunc()', () => { it('should execute function and get data', async() => { - const ctx = getCtx(userWithPrivileges); try { const options = {transaction: tx}; @@ -137,7 +125,7 @@ describe('Application execute()/executeProc()/executeFunc()', () => { }); it('should execute function and get data with user with inherited privileges', async() => { - const ctx = getCtx(userWithInheritedPrivileges); + const ctx = {req: {accessToken: {userId: userWithInheritedPrivileges}}}; try { const options = {transaction: tx}; diff --git a/loopback/common/methods/schema/model-info.js b/loopback/common/methods/schema/model-info.js index 0648deb80..74d764475 100644 --- a/loopback/common/methods/schema/model-info.js +++ b/loopback/common/methods/schema/model-info.js @@ -92,6 +92,7 @@ module.exports = Self => { const locale = modelLocale && modelLocale.get(lang); json[modelName] = { + http: model.sharedClass.http.path, properties: model.definition.rawProperties, validations: jsonValidations, locale diff --git a/loopback/common/methods/vn-model/specs/crud.spec.js b/loopback/common/methods/vn-model/specs/crud.spec.js index 56af72bd9..28b256ad8 100644 --- a/loopback/common/methods/vn-model/specs/crud.spec.js +++ b/loopback/common/methods/vn-model/specs/crud.spec.js @@ -1,20 +1,7 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('Model crud()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); let insertId; const barcodeModel = app.models.ItemBarcode; diff --git a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js index a3dba14d7..84c0784c9 100644 --- a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js +++ b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js @@ -1,20 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('Model rewriteDbError()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should extend rewriteDbError properties to any model passed', () => { const exampleModel = models.ItemTag; diff --git a/modules/claim/back/methods/claim/specs/filter.spec.js b/modules/claim/back/methods/claim/specs/filter.spec.js index 872f49aa3..1ef808e9d 100644 --- a/modules/claim/back/methods/claim/specs/filter.spec.js +++ b/modules/claim/back/methods/claim/specs/filter.spec.js @@ -2,15 +2,7 @@ const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models; describe('claim filter()', () => { - let ctx; - beforeEach(() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - } - }; - }); + const ctx = beforeAll.getCtx(); it('should return 1 result filtering by id', async() => { const tx = await app.models.Claim.beginTransaction({}); diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index 95c356374..55d76ed7a 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -1,18 +1,11 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('claim regularizeClaim()', () => { const userId = 18; - const ctx = { - req: { - accessToken: {userId: userId}, - headers: {origin: 'http://localhost'} - } - }; + const ctx = beforeAll.mockLoopBackContext(userId); ctx.req.__ = (value, params) => { return params.nickname; }; - const chatModel = models.Chat; const claimId = 1; const ticketId = 1; @@ -40,20 +33,6 @@ describe('claim regularizeClaim()', () => { return await models.ClaimEnd.create(claimEnds, options); } - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); - it('should send a chat message with value "Trash" and then change claim state to resolved', async() => { const tx = await models.Claim.beginTransaction({}); diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index b7725e7f8..e1eec59d1 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -1,22 +1,10 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); const i18n = require('i18n'); describe('Update Claim', () => { let url; let claimStatesMap = {}; + beforeAll.mockLoopBackContext(); beforeAll(async() => { - url = await app.models.Url.getUrl(); - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); const claimStates = await app.models.ClaimState.find(); claimStatesMap = claimStates.reduce((acc, state) => ({...acc, [state.code]: state.id}), {}); }); diff --git a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js index 99436fed6..bc081ed08 100644 --- a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js @@ -1,20 +1,7 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('Update Claim', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); const newDate = Date.vnNew(); const original = { ticketFk: 3, diff --git a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js index 74d80b964..1a186f93c 100644 --- a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js +++ b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js @@ -1,23 +1,10 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('Client addressesPropagateRe', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; + beforeAll.mockLoopBackContext(); - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); - - it('should propagate the isEqualizated on both addresses of Mr Wayne and set hasToInvoiceByAddress to false', async() => { + it('should propagate the isEqualizated on both addresses of Mr Wayne' + + ' and set hasToInvoiceByAddress to false', async() => { const tx = await models.Client.beginTransaction({}); try { diff --git a/modules/client/back/methods/client/specs/createAddress.spec.js b/modules/client/back/methods/client/specs/createAddress.spec.js index ae179cf6c..f4901ff93 100644 --- a/modules/client/back/methods/client/specs/createAddress.spec.js +++ b/modules/client/back/methods/client/specs/createAddress.spec.js @@ -1,5 +1,4 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('Address createAddress', () => { const clientFk = 1101; @@ -7,20 +6,7 @@ describe('Address createAddress', () => { const incotermsFk = 'FAS'; const customAgentOneId = 1; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should throw a non uee member error if no incoterms is defined', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index 04fc51a26..5b1ff5da9 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -1,6 +1,4 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); - describe('Client Create', () => { const newAccount = { userName: 'deadpool', @@ -16,20 +14,7 @@ describe('Client Create', () => { const newAccountWithoutEmail = JSON.parse(JSON.stringify(newAccount)); delete newAccountWithoutEmail.email; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it(`should not find deadpool as he's not created yet`, async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/getCard.spec.js b/modules/client/back/methods/client/specs/getCard.spec.js index 962e0a2d4..49e5ed5a4 100644 --- a/modules/client/back/methods/client/specs/getCard.spec.js +++ b/modules/client/back/methods/client/specs/getCard.spec.js @@ -1,11 +1,11 @@ const models = require('vn-loopback/server/server').models; describe('Client getCard()', () => { + const ctx = beforeAll.getCtx(); it('should receive a formated card of Bruce Wayne', async() => { const tx = await models.Client.beginTransaction({}); try { - const ctx = {req: {accessToken: {userId: 9}}}; const options = {transaction: tx}; const id = 1101; diff --git a/modules/client/back/methods/client/specs/getDebt.spec.js b/modules/client/back/methods/client/specs/getDebt.spec.js index b3b5286c0..d89d671a3 100644 --- a/modules/client/back/methods/client/specs/getDebt.spec.js +++ b/modules/client/back/methods/client/specs/getDebt.spec.js @@ -1,9 +1,9 @@ const models = require('vn-loopback/server/server').models; describe('client getDebt()', () => { + const ctx = beforeAll.getCtx(); it('should return the client debt', async() => { const tx = await models.Client.beginTransaction({}); - const ctx = {req: {accessToken: {userId: 9}}}; try { const options = {transaction: tx}; diff --git a/modules/client/back/methods/client/specs/sendSms.spec.js b/modules/client/back/methods/client/specs/sendSms.spec.js index df680c55f..bba9f83ce 100644 --- a/modules/client/back/methods/client/specs/sendSms.spec.js +++ b/modules/client/back/methods/client/specs/sendSms.spec.js @@ -1,12 +1,12 @@ const models = require('vn-loopback/server/server').models; describe('client sendSms()', () => { + const ctx = beforeAll.getCtx(); it('should now send a message and log it', async() => { const tx = await models.Client.beginTransaction({}); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}}; const id = 1101; const destination = 222222222; const message = 'this is the message created in a test'; diff --git a/modules/client/back/methods/client/specs/summary.spec.js b/modules/client/back/methods/client/specs/summary.spec.js index 227f4c398..fe2af8028 100644 --- a/modules/client/back/methods/client/specs/summary.spec.js +++ b/modules/client/back/methods/client/specs/summary.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('client summary()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); it('should return a summary object containing data', async() => { const clientId = 1101; const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/updateAddress.spec.js b/modules/client/back/methods/client/specs/updateAddress.spec.js index 6f02323c5..68981f8b7 100644 --- a/modules/client/back/methods/client/specs/updateAddress.spec.js +++ b/modules/client/back/methods/client/specs/updateAddress.spec.js @@ -1,6 +1,4 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); - describe('Address updateAddress', () => { const clientId = 1101; const addressId = 1; @@ -14,20 +12,7 @@ describe('Address updateAddress', () => { } }; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should throw the non uee member error if no incoterms is defined', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 851648658..8ed55b856 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -99,6 +99,10 @@ module.exports = Self => { { arg: 'hasElectronicInvoice', type: 'boolean' + }, + { + arg: 'hasDailyInvoice', + type: 'boolean' } ], returns: { @@ -117,8 +121,6 @@ module.exports = Self => { const myOptions = {}; const models = Self.app.models; const args = ctx.args; - const userId = ctx.req.accessToken.userId; - const $t = ctx.req.__; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index fc1254dd8..e6690ee5f 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -5,7 +5,7 @@ "AddressObservation": { "dataSource": "vn" }, - "AddressShortage": { + "AddressWaste": { "dataSource": "vn" }, "BankEntity": { diff --git a/modules/client/back/models/addressShortage.json b/modules/client/back/models/address-waste.json similarity index 70% rename from modules/client/back/models/addressShortage.json rename to modules/client/back/models/address-waste.json index 1ae8d986c..2d7126eae 100644 --- a/modules/client/back/models/addressShortage.json +++ b/modules/client/back/models/address-waste.json @@ -1,15 +1,19 @@ { - "name": "AddressShortage", + "name": "AddressWaste", "base": "VnModel", "options": { "mysql": { - "table": "addressShortage" + "table": "addressWaste" } }, "properties": { "addressFk": { "type": "number", "id": true + }, + "type": { + "type": "string", + "id": true } }, "relations": { diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index f3eb9919b..f24f69ae7 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -144,6 +144,9 @@ }, "recommendedCredit": { "type": "number" + }, + "hasDailyInvoice": { + "type": "boolean" } }, diff --git a/modules/client/back/models/specs/address.spec.js b/modules/client/back/models/specs/address.spec.js index f0b421d35..3eae1b1bf 100644 --- a/modules/client/back/models/specs/address.spec.js +++ b/modules/client/back/models/specs/address.spec.js @@ -1,24 +1,10 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('loopback model address', () => { let createdAddressId; const clientId = 1101; - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - beforeAll(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); afterAll(async() => { const client = await models.Client.findById(clientId); diff --git a/modules/entry/back/methods/entry/buyLabel.js b/modules/entry/back/methods/entry/buyLabel.js index 650b05c97..d9b0ebf1d 100644 --- a/modules/entry/back/methods/entry/buyLabel.js +++ b/modules/entry/back/methods/entry/buyLabel.js @@ -29,7 +29,8 @@ module.exports = Self => { http: { path: '/:id/buy-label', verb: 'GET' - } + }, + accessScopes: ['DEFAULT', 'read:multimedia'] }); Self.buyLabel = (ctx, id) => Self.printReport(ctx, id, 'buy-label'); diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 1cd12b737..5963e9c72 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -1,4 +1,3 @@ - const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; const buildFilter = require('vn-loopback/util/filter').buildFilter; const mergeFilters = require('vn-loopback/util/filter').mergeFilters; @@ -95,6 +94,11 @@ module.exports = Self => { arg: 'to', type: 'date', description: `The to date filter` + }, + { + arg: 'days', + type: 'number', + description: `N days interval` } ], returns: { @@ -112,7 +116,6 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const conn = Self.dataSource.connector; const where = buildFilter(ctx.args, (param, value) => { switch (param) { @@ -146,7 +149,13 @@ module.exports = Self => { } }); filter = mergeFilters(ctx.args.filter, {where}); - + const userId = ctx.req.accessToken.userId; + const client = await Self.app.models.Client.findById(userId, myOptions); + const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions); + if (supplier) { + if (!filter.where) filter.where = {}; + filter.where[`e.supplierFk`] = supplier.id; + } const stmts = []; let stmt; stmt = new ParameterizedSQL( @@ -158,7 +167,7 @@ module.exports = Self => { e.invoiceNumber, e.isBooked, e.isExcludedFromAvailable, - e.evaNotes AS observation, + e.evaNotes observation, e.isConfirmed, e.isOrdered, e.isRaid, @@ -170,17 +179,32 @@ module.exports = Self => { e.gestDocFk, e.invoiceInFk, t.landed, - s.name AS supplierName, - s.nickname AS supplierAlias, - co.code AS companyCode, - cu.code AS currencyCode + s.name supplierName, + s.nickname supplierAlias, + co.code companyCode, + cu.code currencyCode, + t.shipped, + t.landed, + t.ref AS travelRef, + t.warehouseInFk, + w.name warehouseInName FROM vn.entry e JOIN vn.supplier s ON s.id = e.supplierFk JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk JOIN vn.company co ON co.id = e.companyFk JOIN vn.currency cu ON cu.id = e.currencyFk` ); + if (ctx.args.days) { + stmt.merge({ + sql: ` + AND t.shipped <= util.VN_CURDATE() + INTERVAL ? DAY + AND t.shipped >= util.VN_CURDATE() + `, + params: [ctx.args.days] + }); + } stmt.merge(conn.makeSuffix(filter)); const itemsIndex = stmts.push(stmt) - 1; diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index 0ed77e8d1..0cb71653e 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -1,7 +1,9 @@ +const UserError = require('vn-loopback/util/user-error'); + const mergeFilters = require('vn-loopback/util/filter').mergeFilters; module.exports = Self => { - Self.remoteMethod('getBuys', { + Self.remoteMethodCtx('getBuys', { description: 'Returns buys for one entry', accessType: 'READ', accepts: [{ @@ -27,13 +29,20 @@ module.exports = Self => { } }); - Self.getBuys = async(id, filter, options) => { + Self.getBuys = async(ctx, id, filter, options) => { + const userId = ctx.req.accessToken.userId; const models = Self.app.models; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); + const client = await Self.app.models.Client.findById(userId, myOptions); + const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions); + if (supplier) { + const isEntryOwner = (await Self.findById(id)).supplierFk === supplier.id; + if (!isEntryOwner) throw new UserError('Access Denied'); + } let defaultFilter = { where: {entryFk: id}, fields: [ @@ -49,9 +58,23 @@ module.exports = Self => { 'buyingValue', 'price2', 'price3', - 'printedStickers' + 'printedStickers', + 'entryFk' ], - include: { + include: [{ + relation: 'entry', + scope: { + fields: [ + 'id', 'supplierFk' + ], + include: { + relation: 'supplier', scope: { + fields: ['id'] + } + } + } + }, + { relation: 'item', scope: { fields: [ @@ -82,9 +105,8 @@ module.exports = Self => { } } } - } + }] }; - defaultFilter = mergeFilters(defaultFilter, filter); return models.Buy.find(defaultFilter, myOptions); diff --git a/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js b/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js index 1b0d4656f..0c8d2729b 100644 --- a/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js +++ b/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js @@ -1,5 +1,4 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('entry addFromPackaging()', () => { const supplier = 442; @@ -7,22 +6,10 @@ describe('entry addFromPackaging()', () => { const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 49}, - http: { - req: { - headers: {origin: 'http://localhost'}, - }, - }, - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx, - }); - }); + beforeAll.mockLoopBackContext(); it('should create an incoming travel', async() => { - const ctx = {args: {isTravelReception: true, supplier}}; + const ctx = {accessToken: {userId: 49}, args: {isTravelReception: true, supplier}}; const tx = await models.Entry.beginTransaction({}); const options = {transaction: tx}; diff --git a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js index 885171ed5..f319c112a 100644 --- a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js @@ -1,21 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('Buy editLatestsBuys()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should change the value of a given column for the selected buys', async() => { const tx = await models.Buy.beginTransaction({}); diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index 28763bc81..c7156062a 100644 --- a/modules/entry/back/methods/entry/specs/filter.spec.js +++ b/modules/entry/back/methods/entry/specs/filter.spec.js @@ -9,7 +9,8 @@ describe('Entry filter()', () => { const ctx = { args: { search: 1 - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); @@ -32,12 +33,13 @@ describe('Entry filter()', () => { const ctx = { args: { currencyFk: 1 - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(9); + expect(result.length).toEqual(11); await tx.rollback(); } catch (e) { @@ -46,26 +48,73 @@ describe('Entry filter()', () => { } }); - it('should return the entry matching the supplier', async() => { - const tx = await models.Entry.beginTransaction({}); - const options = {transaction: tx}; + describe('should return the entry matching the supplier', () => { + it('when userId is supplier ', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; - try { - const ctx = { - args: { - supplierFk: 2 - } - }; + try { + const ctx = { + args: {days: 6}, + req: {accessToken: {userId: 1102}} + }; - const result = await models.Entry.filter(ctx, options); + const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(6); + expect(result.length).toEqual(2); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('when userId is supplier fetching other supplier', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + + try { + const ctx = { + args: { + supplierFk: 1 + }, + req: {accessToken: {userId: 1102}} + }; + + const result = await models.Entry.filter(ctx, options); + + expect(result.length).toEqual(8); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('when userId is not supplier', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + + try { + const ctx = { + args: { + supplierFk: 2 + }, + req: {accessToken: {userId: 9}} + }; + + const result = await models.Entry.filter(ctx, options); + + expect(result.length).toEqual(8); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); it('should return the entry matching the company', async() => { @@ -76,12 +125,13 @@ describe('Entry filter()', () => { const ctx = { args: { companyFk: 442 - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(8); + expect(result.length).toEqual(10); await tx.rollback(); } catch (e) { @@ -98,7 +148,8 @@ describe('Entry filter()', () => { const ctx = { args: { isBooked: true, - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); @@ -121,7 +172,8 @@ describe('Entry filter()', () => { args: { reference: 'movement', travelFk: '2' - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); diff --git a/modules/entry/back/methods/entry/specs/getBuys.spec.js b/modules/entry/back/methods/entry/specs/getBuys.spec.js index cf4462e48..2d3531249 100644 --- a/modules/entry/back/methods/entry/specs/getBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/getBuys.spec.js @@ -1,24 +1,82 @@ +const UserError = require('vn-loopback/util/user-error'); const models = require('vn-loopback/server/server').models; describe('entry getBuys()', () => { const entryId = 4; - it('should get the buys and items of an entry', async() => { - const tx = await models.Entry.beginTransaction({}); - const options = {transaction: tx}; + describe('should get the buys and items of an entry ', () => { + it('when is supplier and entry owner', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; - try { - const result = await models.Entry.getBuys(entryId, options); + try { + const ctx = { + args: { + search: 1 + }, + req: {accessToken: {userId: 2}} + }; - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + const result = await models.Entry.getBuys(ctx, entryId, options); - expect(result.length).toEqual(4); - expect(anyResult.item).toBeDefined(); + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + expect(result.length).toEqual(4); + expect(anyResult.item).toBeDefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('when is supplier but not entry owner', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + const entryId = 1; + try { + const ctx = { + args: { + search: 1 + }, + req: {accessToken: {userId: 1102}} + }; + + const result = await models.Entry.getBuys(ctx, entryId, options); + + expect(result).toBeUndefined(); + } catch (error) { + expect(error).toBeInstanceOf(UserError); + expect(error.message).toBe('Access Denied'); + } + }); + + it('when is not supplier', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + + try { + const ctx = { + args: { + search: 1 + }, + req: {accessToken: {userId: 9}} + }; + + const result = await models.Entry.getBuys(ctx, entryId, options); + + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + expect(result.length).toEqual(4); + expect(anyResult.item).toBeDefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); }); diff --git a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js index c860e228e..fb3268901 100644 --- a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js +++ b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js @@ -1,14 +1,8 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); -const activeCtx = {accessToken: {userId: 9}}; describe('entry importBuysPreview()', () => { const entryId = 1; - beforeAll(async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should return the buys with the calculated packagingFk', async() => { const tx = await models.Entry.beginTransaction({}); diff --git a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js index f21dad9f2..2105cd9c0 100644 --- a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js @@ -1,15 +1,7 @@ -const LoopBackContext = require('loopback-context'); const models = require('vn-loopback/server/server').models; describe('invoiceInDueDay new()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should correctly create a new due day', async() => { const userId = 9; diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js index 436306aab..cf1e0ac2d 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js @@ -1,24 +1,11 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('invoiceIn clone()', () => { - let ctx; + const ctx = beforeAll.getCtx(); let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.Sale.beginTransaction({}); options.transaction = tx; @@ -28,7 +15,8 @@ describe('invoiceIn clone()', () => { await tx.rollback(); }); - it('should return the cloned invoiceIn and also clone invoiceInDueDays and invoiceInTaxes if there are any referencing the invoiceIn', async() => { + it('should return the cloned invoiceIn and also clone invoiceInDueDays ' + + 'and invoiceInTaxes if there are any referencing the invoiceIn', async() => { const clone = await models.InvoiceIn.clone(ctx, 1, false, options); expect(clone.supplierRef).toEqual('1234(2)'); @@ -51,7 +39,8 @@ describe('invoiceIn clone()', () => { expect(invoiceInDueDay.length).toEqual(2); }); - it('should return the cloned invoiceIn and also clone invoiceInIntrastat and invoiceInTaxes if it is rectificative', async() => { + it('should return the cloned invoiceIn and also clone invoiceInIntrastat ' + + 'and invoiceInTaxes if it is rectificative', async() => { const clone = await models.InvoiceIn.clone(ctx, 1, true, options); expect(clone.supplierRef).toEqual('1234(2)'); diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js index 1047cd028..c63f02439 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js @@ -1,24 +1,11 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('invoiceIn corrective()', () => { - let ctx; + const ctx = beforeAll.getCtx(); let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.Sale.beginTransaction({}); options.transaction = tx; diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js index 3af7542ca..bebc9a8e4 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('invoiceOut book()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); const invoiceOutId = 5; it('should update the booked property', async() => { diff --git a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js index 823406500..335159de5 100644 --- a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js +++ b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js @@ -1,24 +1,13 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('upsertFixedPrice()', () => { const now = Date.vnNew(); const fixedPriceId = 1; let originalFixedPrice; + beforeAll.mockLoopBackContext(); beforeAll(async() => { originalFixedPrice = await models.FixedPrice.findById(fixedPriceId); - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); }); it(`should toggle the hasMinPrice boolean if there's a minPrice and update the rest of the data`, async() => { diff --git a/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js index 3f4917477..3b0a65e61 100644 --- a/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js @@ -1,13 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving getAlternative()', () => { - beforeAll(async() => { - ctx = { - req: { - headers: {origin: 'http://localhost'}, - } - }; - }); + beforeAll.mockLoopBackContext(); it('should return a list of items without alternatives', async() => { const shelvingFk = 'HEJ'; diff --git a/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js b/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js index 2dd43224c..f01cb985d 100644 --- a/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js +++ b/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js @@ -1,25 +1,13 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('ItemShelving upsertItem()', () => { const warehouseFk = 1; - let ctx; + + const ctx = beforeAll.getCtx(); let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.ItemShelving.beginTransaction({}); options.transaction = tx; diff --git a/modules/item/back/methods/item/specs/clone.spec.js b/modules/item/back/methods/item/specs/clone.spec.js index 01210677e..5bb5fe560 100644 --- a/modules/item/back/methods/item/specs/clone.spec.js +++ b/modules/item/back/methods/item/specs/clone.spec.js @@ -1,21 +1,8 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('item clone()', () => { let nextItemId; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); beforeEach(async() => { let query = `SELECT i1.id + 1 as id FROM vn.item i1 diff --git a/modules/item/back/methods/item/specs/getBalance.spec.js b/modules/item/back/methods/item/specs/getBalance.spec.js index 728b5f33e..95de3cc50 100644 --- a/modules/item/back/methods/item/specs/getBalance.spec.js +++ b/modules/item/back/methods/item/specs/getBalance.spec.js @@ -2,17 +2,14 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('item getBalance()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); it('should return the balance lines of a client type loses in which one has highlighted true', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { - const activeCtx = { - accessToken: {userId: 9}, - }; spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx + active: ctx }); const losesClientId = 1111; const ticket = await models.Ticket.findById(7, null, options); @@ -64,7 +61,7 @@ describe('item getBalance()', () => { const secondItemBalance = await models.Item.getBalance(ctx, secondFilter, options); expect(firstItemBalance[9].claimFk).toEqual(null); - expect(secondItemBalance[7].claimFk).toEqual(2); + expect(secondItemBalance[7].claimFk).toEqual(1); await tx.rollback(); } catch (e) { diff --git a/modules/item/back/methods/item/specs/new.spec.js b/modules/item/back/methods/item/specs/new.spec.js index 2ffaf87a5..11570ffb9 100644 --- a/modules/item/back/methods/item/specs/new.spec.js +++ b/modules/item/back/methods/item/specs/new.spec.js @@ -1,21 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('item new()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.getCtx(); it('should create a new item, adding the name as a tag', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/methods/item/specs/regularize.spec.js b/modules/item/back/methods/item/specs/regularize.spec.js index e7df9a003..4e94d5d6d 100644 --- a/modules/item/back/methods/item/specs/regularize.spec.js +++ b/modules/item/back/methods/item/specs/regularize.spec.js @@ -1,27 +1,13 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('regularize()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 18}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.mockLoopBackContext(18); it('should create a new ticket and add a line', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { - const ctx = {req: {accessToken: {userId: 18}}}; const itemId = 1; const warehouseId = 1; const quantity = 11; diff --git a/modules/item/back/methods/item/specs/updateTaxes.spec.js b/modules/item/back/methods/item/specs/updateTaxes.spec.js index 793e43de8..828a5fec9 100644 --- a/modules/item/back/methods/item/specs/updateTaxes.spec.js +++ b/modules/item/back/methods/item/specs/updateTaxes.spec.js @@ -1,20 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('item updateTaxes()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should throw an error if the taxClassFk is blank', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/methods/tag/specs/onSubmit.spec.js b/modules/item/back/methods/tag/specs/onSubmit.spec.js index 1e96d9e81..e92a5fcdf 100644 --- a/modules/item/back/methods/tag/specs/onSubmit.spec.js +++ b/modules/item/back/methods/tag/specs/onSubmit.spec.js @@ -1,20 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('tag onSubmit()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should delete a tag', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/model-config.json b/modules/item/back/model-config.json index 2d06e1ada..5dbe4d62a 100644 --- a/modules/item/back/model-config.json +++ b/modules/item/back/model-config.json @@ -32,6 +32,9 @@ "ItemLog": { "dataSource": "vn" }, + "ItemMinimumQuantity": { + "dataSource": "vn" + }, "ItemPackingType": { "dataSource": "vn" }, diff --git a/modules/item/back/models/item-minimum-quantity.json b/modules/item/back/models/item-minimum-quantity.json new file mode 100644 index 000000000..74eac39fc --- /dev/null +++ b/modules/item/back/models/item-minimum-quantity.json @@ -0,0 +1,63 @@ +{ + "name": "ItemMinimumQuantity", + "base": "VnModel", + "options": { + "mysql": { + "table": "itemMinimumQuantity" + } + }, + "mixins": { + "Loggable": true + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Id" + }, + "itemFk": { + "type": "number", + "required": true + }, + "quantity": { + "type": "number", + "required": true + }, + "started": { + "type": "date", + "required": true + }, + "ended": { + "type": "date" + }, + "warehouseFk": { + "type": "number" + }, + "created": { + "type": "date" + }, + "editorFk": { + "type": "number" + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "buyer", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 10cff3e04..eda56e938 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -152,10 +152,6 @@ "columnName": "doPhoto" } }, - "minQuantity": { - "type": "number", - "description": "Min quantity" - }, "photoMotivation": { "type": "string" } diff --git a/modules/item/back/models/specs/itemMinimumQuantity.spec.js b/modules/item/back/models/specs/itemMinimumQuantity.spec.js new file mode 100644 index 000000000..072a80f94 --- /dev/null +++ b/modules/item/back/models/specs/itemMinimumQuantity.spec.js @@ -0,0 +1,101 @@ +const {models} = require('vn-loopback/server/server'); + +describe('itemMinimumQuantity model', () => { + const itemFk = 5; + const warehouseFk = 60; + + beforeAll(async() => { + await models.ItemMinimumQuantity.destroyAll({where: {itemFk: itemFk}}); + }); + + describe('CRUD operations', () => { + it('should create a new itemMinimumQuantity record', async() => { + const newRecord = { + itemFk: itemFk, + quantity: 100, + started: Date.vnNew(), + ended: new Date(Date.vnNew().setFullYear(Date.vnNew().getFullYear() + 1)), + warehouseFk: warehouseFk + }; + + const createdRecord = await models.ItemMinimumQuantity.create(newRecord); + + expect(createdRecord).toBeDefined(); + expect(createdRecord.quantity).toEqual(newRecord.quantity); + }); + + it('should read an existing itemMinimumQuantity record', async() => { + const newRecord = { + itemFk: itemFk, + quantity: 100, + started: Date.vnNew(), + ended: new Date(Date.vnNew().setFullYear(Date.vnNew().getFullYear() + 2)), + warehouseFk: warehouseFk + }; + + await models.ItemMinimumQuantity.create(newRecord); + + const existingRecord = await models.ItemMinimumQuantity.findOne({where: {itemFk: itemFk}}); + + expect(existingRecord).toBeDefined(); + expect(existingRecord.itemFk).toEqual(itemFk); + }); + + it('should update an existing itemMinimumQuantity record', async() => { + const newRecord = { + itemFk: itemFk, + quantity: 100, + started: Date.vnNew(), + ended: new Date(Date.vnNew().setFullYear(Date.vnNew().getFullYear() + 3)), + warehouseFk: warehouseFk + }; + + await models.ItemMinimumQuantity.create(newRecord); + + const newQuantity = 150; + const existingRecord = await models.ItemMinimumQuantity.findOne({where: {itemFk: itemFk}}); + existingRecord.quantity = newQuantity; + + await existingRecord.save(); + const updatedRecord = await models.ItemMinimumQuantity.findOne({where: {itemFk: itemFk}}); + + expect(updatedRecord.quantity).toEqual(newQuantity); + }); + }); + + describe('validation and constraints', () => { + it('should enforce unique constraint on itemFk, started, ended, and warehouseFk', async() => { + const newRecord = { + itemFk: itemFk, + quantity: 100, + started: Date.vnNew(), + ended: Date.vnNew().setFullYear(Date.vnNew().getFullYear() + 5), + warehouseFk: warehouseFk + }; + + try { + await models.ItemMinimumQuantity.create(newRecord); + await models.ItemMinimumQuantity.create(newRecord); + } catch (e) { + expect(e).toBeDefined(); + expect(e.code).toContain('ER_DUP_ENTRY'); + } + }); + + it('should allow null values for ended and warehouseFk', async() => { + const newRecord = { + itemFk: itemFk, + quantity: 100, + started: Date.vnNew(), + ended: null, + warehouseFk: null + }; + + const createdRecord = await models.ItemMinimumQuantity.create(newRecord); + + expect(createdRecord).toBeDefined(); + expect(createdRecord.ended).toBeNull(); + expect(createdRecord.warehouseFk).toBeNull(); + }); + }); +}); diff --git a/modules/item/front/summary/index.html b/modules/item/front/summary/index.html index 13c671d29..0e4cfc955 100644 --- a/modules/item/front/summary/index.html +++ b/modules/item/front/summary/index.html @@ -128,9 +128,6 @@ - -

diff --git a/modules/order/back/methods/order-row/specs/addToOrder.spec.js b/modules/order/back/methods/order-row/specs/addToOrder.spec.js index 96544a1a9..2bc78ffef 100644 --- a/modules/order/back/methods/order-row/specs/addToOrder.spec.js +++ b/modules/order/back/methods/order-row/specs/addToOrder.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order addToOrder()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); const orderId = 8; it('should add a row to a given order', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/order/back/methods/order/catalogFilter.js b/modules/order/back/methods/order/catalogFilter.js index ab1d7784e..27048457c 100644 --- a/modules/order/back/methods/order/catalogFilter.js +++ b/modules/order/back/methods/order/catalogFilter.js @@ -119,7 +119,7 @@ module.exports = Self => { w.firstName, tci.priceKg, ink.hex, - i.minQuantity + tci.minQuantity FROM tmp.ticketCalculateItem tci JOIN vn.item i ON i.id = tci.itemFk JOIN vn.itemType it ON it.id = i.typeFk @@ -158,21 +158,19 @@ module.exports = Self => { // Apply item prices const pricesIndex = stmts.push( - `SELECT - tcp.itemFk, + `SELECT tcp.itemFk, tcp.grouping, tcp.price, tcp.rate, tcp.warehouseFk, tcp.priceKg, - w.name AS warehouse + w.name warehouse FROM tmp.ticketComponentPrice tcp JOIN vn.warehouse w ON w.id = tcp.warehouseFk`) - 1; // Get tags from all items const itemTagsIndex = stmts.push( - `SELECT - t.id, + `SELECT t.id, t.name, t.isFree, t.sourceTable, diff --git a/modules/order/back/methods/order/specs/filter.spec.js b/modules/order/back/methods/order/specs/filter.spec.js index 68de7fe04..9e644bb2d 100644 --- a/modules/order/back/methods/order/specs/filter.spec.js +++ b/modules/order/back/methods/order/specs/filter.spec.js @@ -1,11 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order filter()', () => { - const ctx = { - req: {accessToken: {userId: 9}}, - args: {}, - params: {} - }; + const ctx = beforeAll.getCtx(); it('should call the filter method with a basic search', async() => { const myCtx = Object.assign({}, ctx); diff --git a/modules/order/back/methods/order/specs/new.spec.js b/modules/order/back/methods/order/specs/new.spec.js index c43527f66..779de6ada 100644 --- a/modules/order/back/methods/order/specs/new.spec.js +++ b/modules/order/back/methods/order/specs/new.spec.js @@ -2,7 +2,7 @@ const models = require('vn-loopback/server/server').models; const UserError = require('vn-loopback/util/user-error'); describe('order new()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); it('should throw an error if the client isnt active', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/order/back/methods/order/specs/newFromTicket.spec.js b/modules/order/back/methods/order/specs/newFromTicket.spec.js index c509552fe..d927a0338 100644 --- a/modules/order/back/methods/order/specs/newFromTicket.spec.js +++ b/modules/order/back/methods/order/specs/newFromTicket.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order newFromTicket()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); it('should create a new order from an existing ticket', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/order/front/catalog-view/index.html b/modules/order/front/catalog-view/index.html index 081ce05a0..b047e1e6a 100644 --- a/modules/order/front/catalog-view/index.html +++ b/modules/order/front/catalog-view/index.html @@ -37,18 +37,18 @@ value="{{::item.value7}}"> - - - - - - {{::item.minQuantity}} - + + + + + + {{::item.minQuantity}} +