7226-testToMaster_2416 #2320

Merged
alexm merged 188 commits from 7226-testToMaster_2416 into master 2024-04-18 05:39:36 +00:00
111 changed files with 1563 additions and 1060 deletions
Showing only changes of commit d8da317339 - Show all commits

View File

@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2414.01] - 2024-04-04
### Added
### Changed
### Fixed
## [2408.01] - 2024-02-22 ## [2408.01] - 2024-02-22
### Added ### Added

View File

@ -29,7 +29,8 @@ module.exports = Self => {
http: { http: {
path: `/:id/downloadFile`, path: `/:id/downloadFile`,
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.downloadFile = async function(ctx, id) { Self.downloadFile = async function(ctx, id) {

View File

@ -42,7 +42,8 @@ module.exports = Self => {
http: { http: {
path: `/:id/download`, path: `/:id/download`,
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.download = async function(id, fileCabinet, filter) { Self.download = async function(id, fileCabinet, filter) {

View File

@ -47,7 +47,8 @@ module.exports = Self => {
http: { http: {
path: `/:collection/:size/:id/download`, path: `/:collection/:size/:id/download`,
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.download = async function(ctx, collection, size, id) { Self.download = async function(ctx, collection, size, id) {

View File

@ -49,6 +49,7 @@ describe('MRWConfig createShipment()', () => {
await models.MrwConfig.create( await models.MrwConfig.create(
{ {
'id': 1,
'url': 'https://url.com', 'url': 'https://url.com',
'user': 'user', 'user': 'user',
'password': 'password', 'password': 'password',

View File

@ -7,7 +7,7 @@ describe('NotificationSubscription getList()', () => {
const notifications = await models.Notification.find({}); const notifications = await models.Notification.find({});
const totalAvailable = notifications.length - active.length; const totalAvailable = notifications.length - active.length;
expect(active.length).toEqual(2); expect(active.length).toEqual(3);
expect(available.length).toEqual(totalAvailable); expect(available.length).toEqual(totalAvailable);
}); });
}); });

View File

@ -0,0 +1,27 @@
module.exports = Self => {
Self.remoteMethodCtx('shareToken', {
description: 'Returns token to view files or images and share it',
accessType: 'WRITE',
accepts: [],
returns: {
type: 'Object',
root: true
},
http: {
path: `/shareToken`,
verb: 'GET'
}
});
Self.shareToken = async function(ctx) {
const {accessToken: token} = ctx.req;
const user = await Self.findById(token.userId);
const multimediaToken = await user.accessTokens.create({
scopes: ['read:multimedia']
});
return {multimediaToken};
};
};

View File

@ -0,0 +1,27 @@
const {models} = require('vn-loopback/server/server');
describe('Share Token', () => {
let ctx = null;
beforeAll(async() => {
const unAuthCtx = {
req: {
headers: {},
connection: {
remoteAddress: '127.0.0.1'
},
getLocale: () => 'en'
},
args: {}
};
let login = await models.VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare');
let accessToken = await models.AccessToken.findById(login.token);
ctx = {req: {accessToken: accessToken}};
});
it('should renew token', async() => {
const multimediaToken = await models.VnUser.shareToken(ctx);
expect(Object.keys(multimediaToken).length).toEqual(1);
expect(multimediaToken.multimediaToken.userId).toEqual(ctx.req.accessToken.userId);
expect(multimediaToken.multimediaToken.scopes[0]).toEqual('read:multimedia');
});
});

View File

@ -16,7 +16,7 @@
"Accounting": { "Accounting": {
"dataSource": "vn" "dataSource": "vn"
}, },
"Buyer": { "Buyer": {
"dataSource": "vn" "dataSource": "vn"
}, },
"Campaign": { "Campaign": {
@ -94,6 +94,9 @@
"Module": { "Module": {
"dataSource": "vn" "dataSource": "vn"
}, },
"MrwConfig": {
"dataSource": "vn"
},
"Notification": { "Notification": {
"dataSource": "vn" "dataSource": "vn"
}, },
@ -166,10 +169,10 @@
"VnRole": { "VnRole": {
"dataSource": "vn" "dataSource": "vn"
}, },
"MrwConfig": { "WorkerActivity": {
"dataSource": "vn"
},
"WorkerActivityType": {
"dataSource": "vn" "dataSource": "vn"
} }
} }

View File

@ -9,6 +9,7 @@
"properties": { "properties": {
"id": { "id": {
"type": "number", "type": "number",
"id": true,
"required": true "required": true
}, },
"url": { "url": {

View File

@ -13,6 +13,7 @@ module.exports = function(Self) {
require('../methods/vn-user/privileges')(Self); require('../methods/vn-user/privileges')(Self);
require('../methods/vn-user/validate-auth')(Self); require('../methods/vn-user/validate-auth')(Self);
require('../methods/vn-user/renew-token')(Self); require('../methods/vn-user/renew-token')(Self);
require('../methods/vn-user/share-token')(Self);
require('../methods/vn-user/update-user')(Self); require('../methods/vn-user/update-user')(Self);
Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create'); Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create');

View File

@ -1,129 +1,140 @@
{ {
"name": "VnUser", "name": "VnUser",
"base": "User", "base": "User",
"validateUpsert": true, "validateUpsert": true,
"options": { "options": {
"mysql": { "mysql": {
"table": "account.user" "table": "account.user"
} }
}, },
"mixins": { "mixins": {
"Loggable": true "Loggable": true
}, },
"resetPasswordTokenTTL": "604800", "resetPasswordTokenTTL": "604800",
"properties": { "properties": {
"id": { "id": {
"type": "number", "type": "number",
"id": true "id": true
}, },
"name": { "name": {
"type": "string", "type": "string",
"required": true "required": true
}, },
"username": { "username": {
"type": "string" "type": "string"
}, },
"roleFk": { "roleFk": {
"type": "number", "type": "number",
"mysql": { "mysql": {
"columnName": "role" "columnName": "role"
} }
}, },
"nickname": { "nickname": {
"type": "string" "type": "string"
}, },
"lang": { "lang": {
"type": "string" "type": "string"
}, },
"active": { "active": {
"type": "boolean" "type": "boolean"
}, },
"email": { "email": {
"type": "string" "type": "string"
}, },
"emailVerified": { "emailVerified": {
"type": "boolean" "type": "boolean"
}, },
"created": { "created": {
"type": "date" "type": "date"
}, },
"updated": { "updated": {
"type": "date" "type": "date"
}, },
"image": { "image": {
"type": "string" "type": "string"
}, },
"hasGrant": { "hasGrant": {
"type": "boolean" "type": "boolean"
}, },
"passExpired": { "passExpired": {
"type": "date" "type": "date"
}, },
"twoFactor": { "twoFactor": {
"type": "string" "type": "string"
} }
}, },
"relations": { "relations": {
"role": { "role": {
"type": "belongsTo", "type": "belongsTo",
"model": "VnRole", "model": "VnRole",
"foreignKey": "roleFk" "foreignKey": "roleFk"
}, },
"roles": { "roles": {
"type": "hasMany", "type": "hasMany",
"model": "RoleRole", "model": "RoleRole",
"foreignKey": "role", "foreignKey": "role",
"primaryKey": "roleFk" "primaryKey": "roleFk"
}, },
"emailUser": { "emailUser": {
"type": "hasOne", "type": "hasOne",
"model": "EmailUser", "model": "EmailUser",
"foreignKey": "userFk" "foreignKey": "userFk"
}, },
"worker": { "worker": {
"type": "hasOne", "type": "hasOne",
"model": "Worker", "model": "Worker",
"foreignKey": "id" "foreignKey": "id"
}, },
"userConfig": { "userConfig": {
"type": "hasOne", "type": "hasOne",
"model": "UserConfig", "model": "UserConfig",
"foreignKey": "userFk" "foreignKey": "userFk"
} }
}, },
"acls": [ "acls": [
{ {
"property": "signIn", "property": "signIn",
"accessType": "EXECUTE", "accessType": "EXECUTE",
"principalType": "ROLE", "principalType": "ROLE",
"principalId": "$everyone", "principalId": "$everyone",
"permission": "ALLOW" "permission": "ALLOW"
}, { },
"property": "recoverPassword", {
"accessType": "EXECUTE", "property": "recoverPassword",
"principalType": "ROLE", "accessType": "EXECUTE",
"principalId": "$everyone", "principalType": "ROLE",
"permission": "ALLOW" "principalId": "$everyone",
}, { "permission": "ALLOW"
"property": "validateAuth", },
"accessType": "EXECUTE", {
"principalType": "ROLE", "property": "validateAuth",
"principalId": "$everyone", "accessType": "EXECUTE",
"permission": "ALLOW" "principalType": "ROLE",
}, { "principalId": "$everyone",
"property": "privileges", "permission": "ALLOW"
"accessType": "*", },
"principalType": "ROLE", {
"principalId": "$authenticated", "property": "privileges",
"permission": "ALLOW" "accessType": "*",
}, { "principalType": "ROLE",
"property": "renewToken", "principalId": "$authenticated",
"accessType": "WRITE", "permission": "ALLOW"
"principalType": "ROLE", },
"principalId": "$authenticated", {
"permission": "ALLOW" "property": "renewToken",
} "accessType": "WRITE",
], "principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
},
{
"property": "shareToken",
"accessType": "WRITE",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
}
],
"scopes": { "scopes": {
"preview": { "preview": {
"fields": [ "fields": [
@ -140,7 +151,7 @@
"hasGrant", "hasGrant",
"realm", "realm",
"email", "email",
"emailVerified" "emailVerified"
] ]
} }
} }

View File

@ -0,0 +1,39 @@
{
"name": "WorkerActivity",
"base": "VnModel",
"options": {
"mysql": {
"table": "workerActivity"
}
},
"properties": {
"id": {
"id": true,
"type": "number"
},
"created": {
"type": "date"
},
"model": {
"type": "string"
},
"event": {
"type": "string"
},
"description": {
"type": "string"
},
"relations": {
"workerFk": {
"type": "belongsTo",
"model": "Worker",
"foreignKey": "workerFk"
},
"workerActivityTypeFk": {
"type": "belongsTo",
"model": "WorkerActivityType",
"foreignKey": "workerActivityTypeFk"
}
}
}
}

View File

@ -0,0 +1,19 @@
{
"name": "WorkerActivityType",
"base": "VnModel",
"options": {
"mysql": {
"table": "workerActivityType"
}
},
"properties": {
"code": {
"id": true,
"type": "string"
},
"description": {
"type": "string",
"required": false
}
}
}

View File

@ -7,8 +7,8 @@ SET foreign_key_checks = 0;
-- XXX: vn-database -- XXX: vn-database
INSERT INTO util.config (environment, mockTime, mockUtcTime, mockEnabled) INSERT INTO util.config (id, environment, mockTime, mockUtcTime, mockEnabled)
VALUES ('local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE); VALUES (1, 'local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE);
/* #5483 /* #5483
INSERT INTO vn.entryConfig (defaultEntry, mailToNotify, inventorySupplierFk, maxLockTime, defaultSupplierFk) INSERT INTO vn.entryConfig (defaultEntry, mailToNotify, inventorySupplierFk, maxLockTime, defaultSupplierFk)
VALUES(1, NULL, 1, 300, 1); VALUES(1, NULL, 1, 300, 1);
@ -70,7 +70,7 @@ UPDATE vn.supplier
UPDATE `vn`.`claimRatio` SET `claimAmount` = '10' WHERE (`clientFk` = '1101'); UPDATE `vn`.`claimRatio` SET `claimAmount` = '10' WHERE (`clientFk` = '1101');
INSERT INTO `vn`.`agency` (`name`, `warehouseFk`, `isOwn`, `isAnyVolumeAllowed`) INSERT INTO `vn`.`agency` (`name`, `warehouseFk`, `isOwn`, `isAnyVolumeAllowed`)
VALUES VALUES
('Agencia', '1', '1', '1'), ('Agencia', '1', '1', '1'),
('Otra agencia ', '1', '0', '0'); ('Otra agencia ', '1', '0', '0');

View File

@ -60,13 +60,13 @@ INSERT INTO `vn`.`ticketConfig` (`id`, `scopeDays`)
VALUES VALUES
('1', '6'); ('1', '6');
INSERT INTO `vn`.`bionicConfig` (`generalInflationCoeficient`, `minimumDensityVolumetricWeight`, `verdnaturaVolumeBox`, `itemCarryBox`) INSERT INTO `vn`.`bionicConfig` (`id`, `generalInflationCoeficient`, `minimumDensityVolumetricWeight`, `verdnaturaVolumeBox`, `itemCarryBox`)
VALUES VALUES
(1.30, 167.00, 138000, 71); (1, 1.30, 167.00, 138000, 71);
INSERT INTO `vn`.`chatConfig` (`host`, `api`) INSERT INTO `vn`.`chatConfig` (`id`, `host`, `api`)
VALUES VALUES
('https://chat.verdnatura.es', 'https://chat.verdnatura.es/api/v1'); (1, 'https://chat.verdnatura.es', 'https://chat.verdnatura.es/api/v1');
INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`) INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`)
VALUES VALUES
@ -592,13 +592,13 @@ INSERT INTO `vn`.`supplierAccount`(`id`, `supplierFk`, `iban`, `bankEntityFk`)
VALUES VALUES
(241, 442, 'ES111122333344111122221111', 128); (241, 442, 'ES111122333344111122221111', 128);
INSERT INTO `vn`.`company`(`id`, `code`, `supplierAccountFk`, `workerManagerFk`, `companyCode`, `sage200Company`, `expired`, `companyGroupFk`, `phytosanitary` , `clientFk`) INSERT INTO `vn`.`company`(`id`, `code`, `supplierAccountFk`, `workerManagerFk`, `companyCode`, `expired`, `companyGroupFk`, `phytosanitary` , `clientFk`)
VALUES VALUES
(69 , 'CCs', NULL, 30, NULL, 0, NULL, 1, NULL , NULL), (69 , 'CCs', NULL, 30, 0, NULL, 1, NULL , NULL),
(442 , 'VNL', 241, 30, 2 , 1, NULL, 2, 'VNL Company - Plant passport' , 1101), (442 , 'VNL', 241, 30, 1, NULL, 2, 'VNL Company - Plant passport' , 1101),
(567 , 'VNH', NULL, 30, NULL, 4, NULL, 1, 'VNH Company - Plant passport' , NULL), (567 , 'VNH', NULL, 30, 4, NULL, 1, 'VNH Company - Plant passport' , NULL),
(791 , 'FTH', NULL, 30, NULL, 3, '2015-11-30', 1, NULL , NULL), (791 , 'FTH', NULL, 30, 3, '2015-11-30', 1, NULL , NULL),
(1381, 'ORN', NULL, 30, NULL, 7, NULL, 1, 'ORN Company - Plant passport' , NULL); (1381, 'ORN', NULL, 30, 7, NULL, 1, 'ORN Company - Plant passport' , NULL);
INSERT INTO `vn`.`taxArea` (`code`, `claveOperacionFactura`, `CodigoTransaccion`) INSERT INTO `vn`.`taxArea` (`code`, `claveOperacionFactura`, `CodigoTransaccion`)
VALUES VALUES
@ -608,7 +608,8 @@ INSERT INTO `vn`.`taxArea` (`code`, `claveOperacionFactura`, `CodigoTransaccion`
('WORLD', 2, 15); ('WORLD', 2, 15);
INSERT INTO vn.invoiceOutConfig INSERT INTO vn.invoiceOutConfig
SET parallelism = 8; SET id = 1,
parallelism = 8;
INSERT INTO `vn`.`invoiceOutSerial` (`code`, `description`, `isTaxed`, `taxAreaFk`, `isCEE`, `type`) INSERT INTO `vn`.`invoiceOutSerial` (`code`, `description`, `isTaxed`, `taxAreaFk`, `isCEE`, `type`)
VALUES VALUES
@ -714,7 +715,7 @@ INSERT INTO `vn`.`zoneClosure` (`zoneFk`, `dated`, `hour`)
(12, util.VN_CURDATE(), '23:59'), (12, util.VN_CURDATE(), '23:59'),
(13, util.VN_CURDATE(), '23:59'); (13, util.VN_CURDATE(), '23:59');
INSERT INTO `vn`.`zoneConfig` (`scope`) VALUES ('1'); INSERT INTO `vn`.`zoneConfig` (`id`, `scope`) VALUES (1, '1');
INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agencyModeFk`, `description`, `m3`, `cost`, `started`, `finished`, `zoneFk`) INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agencyModeFk`, `description`, `m3`, `cost`, `started`, `finished`, `zoneFk`)
VALUES VALUES
@ -759,8 +760,8 @@ INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeF
(29, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (29, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(30, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (30, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL); (32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(33, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL);
INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`)
VALUES VALUES
(1, 11, 1, 'ready'), (1, 11, 1, 'ready'),
@ -983,9 +984,9 @@ INSERT INTO `vn`.`packaging`(`id`, `volume`, `width`, `height`, `depth`, `isPack
('cc', 1640038.00, 56.00, 220.00, 128.00, 1, util.VN_CURDATE(), 15, 90.00), ('cc', 1640038.00, 56.00, 220.00, 128.00, 1, util.VN_CURDATE(), 15, 90.00),
('pallet 100', 2745600.00, 100.00, 220.00, 120.00, 1, util.VN_CURDATE(), 16, 0.00); ('pallet 100', 2745600.00, 100.00, 220.00, 120.00, 1, util.VN_CURDATE(), 16, 0.00);
INSERT INTO `vn`.`packagingConfig`(`upperGap`, `defaultSmallPackageFk`, `defaultBigPackageFk`) INSERT INTO `vn`.`packagingConfig`(`id`, `upperGap`, `defaultSmallPackageFk`, `defaultBigPackageFk`)
VALUES VALUES
('10', 1, 'pallet 100'); (1, '10', 1, 'pallet 100');
INSERT INTO `vn`.`expeditionStateType`(`id`, `description`, `code`) INSERT INTO `vn`.`expeditionStateType`(`id`, `description`, `code`)
VALUES VALUES
@ -1491,8 +1492,8 @@ INSERT INTO `bs`.`waste`(`buyer`, `year`, `week`, `family`, `itemFk`, `itemTypeF
INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packagingFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`) INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packagingFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`)
VALUES VALUES
(1, 1, 1, 50, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), (1, 1, 1, 50, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, util.VN_CURDATE() - INTERVAL 2 MONTH),
(2, 2, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (2, 2, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, util.VN_CURDATE() - INTERVAL 1 MONTH),
(3, 3, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 0, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, util.VN_CURDATE()), (3, 3, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 0, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, util.VN_CURDATE()),
(4, 2, 2, 5, 450, 3, 1, 1.000, 1.000, 0.000, 10, 10, 0, NULL, 0.00, 7.30, 7.00, 0, 1, 0, 2.5, util.VN_CURDATE()), (4, 2, 2, 5, 450, 3, 1, 1.000, 1.000, 0.000, 10, 10, 0, NULL, 0.00, 7.30, 7.00, 0, 1, 0, 2.5, util.VN_CURDATE()),
(5, 3, 3, 55, 500, 5, 1, 1.000, 1.000, 0.000, 1, 1, 0, NULL, 0.00, 78.3, 75.6, 0, 1, 0, 2.5, util.VN_CURDATE()), (5, 3, 3, 55, 500, 5, 1, 1.000, 1.000, 0.000, 1, 1, 0, NULL, 0.00, 78.3, 75.6, 0, 1, 0, 2.5, util.VN_CURDATE()),
@ -1868,8 +1869,7 @@ INSERT INTO `vn`.`claimEnd`(`id`, `saleFk`, `claimFk`, `workerFk`, `claimDestina
INSERT INTO `vn`.`claimConfig`(`id`, `maxResponsibility`) INSERT INTO `vn`.`claimConfig`(`id`, `maxResponsibility`)
VALUES VALUES
(1, 50), (1, 50);
(2, 30);
INSERT INTO `vn`.`claimRatio`(`clientFk`, `yearSale`, `claimAmount`, `claimingRate`, `priceIncreasing`, `packingRate`) INSERT INTO `vn`.`claimRatio`(`clientFk`, `yearSale`, `claimAmount`, `claimingRate`, `priceIncreasing`, `packingRate`)
VALUES VALUES
@ -2504,9 +2504,9 @@ INSERT INTO `hedera`.`imageCollectionSize`(`id`, `collectionFk`,`width`, `height
VALUES VALUES
(1, 4, 160, 160); (1, 4, 160, 160);
INSERT INTO `vn`.`rateConfig`(`rate0`, `rate1`, `rate2`, `rate3`) INSERT INTO `vn`.`rateConfig`(`id`, `rate0`, `rate1`, `rate2`, `rate3`)
VALUES VALUES
(36, 31, 25, 21); (1, 36, 31, 25, 21);
INSERT INTO `vn`.`rate`(`dated`, `warehouseFk`, `rate0`, `rate1`, `rate2`, `rate3`) INSERT INTO `vn`.`rate`(`dated`, `warehouseFk`, `rate0`, `rate1`, `rate2`, `rate3`)
VALUES VALUES
@ -2697,9 +2697,9 @@ INSERT INTO `bs`.`sale` (`saleFk`, `amount`, `dated`, `typeFk`, `clientFk`)
(4, 33.8, util.VN_CURDATE(), 1, 1101), (4, 33.8, util.VN_CURDATE(), 1, 1101),
(30, 34.4, util.VN_CURDATE(), 1, 1108); (30, 34.4, util.VN_CURDATE(), 1, 1108);
INSERT INTO `vn`.`docuwareConfig` (`url`) INSERT INTO `vn`.`docuwareConfig` (`id`, `url`)
VALUES VALUES
('http://docuware.url/'); (1, 'http://docuware.url/');
INSERT INTO `vn`.`calendarHolidaysName` (`id`, `name`) INSERT INTO `vn`.`calendarHolidaysName` (`id`, `name`)
VALUES VALUES
@ -2796,11 +2796,12 @@ INSERT INTO `vn`.`packingSite` (`id`, `code`, `hostFk`, `monitorId`)
VALUES VALUES
(1, 'h1', 1, ''); (1, 'h1', 1, '');
INSERT INTO `vn`.`packingSiteConfig` (`shinobiUrl`, `shinobiToken`, `shinobiGroupKey`, `avgBoxingTime`) INSERT INTO `vn`.`packingSiteConfig` (`id`, `shinobiUrl`, `shinobiToken`, `shinobiGroupKey`, `avgBoxingTime`)
VALUES VALUES
('', 'SHINNOBI_TOKEN', 'GROUP_TOKEN', 6000); (1, '', 'SHINNOBI_TOKEN', 'GROUP_TOKEN', 6000);
INSERT INTO `util`.`notificationConfig` INSERT INTO `util`.`notificationConfig`
SET `cleanDays` = 90; SET `id` = 1,
`cleanDays` = 90;
INSERT INTO `util`.`notification` (`id`, `name`, `description`) INSERT INTO `util`.`notification` (`id`, `name`, `description`)
VALUES VALUES
@ -2809,7 +2810,8 @@ INSERT INTO `util`.`notification` (`id`, `name`, `description`)
(3, 'not-main-printer-configured', 'A printer distinct than main has been configured'), (3, 'not-main-printer-configured', 'A printer distinct than main has been configured'),
(4, 'supplier-pay-method-update', 'A supplier pay method has been updated'), (4, 'supplier-pay-method-update', 'A supplier pay method has been updated'),
(5, 'modified-entry', 'An entry has been modified'), (5, 'modified-entry', 'An entry has been modified'),
(6, 'book-entry-deleted', 'accounting entries deleted'); (6, 'book-entry-deleted', 'accounting entries deleted'),
(7, 'zone-included','An email to notify zoneCollisions');
INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`)
VALUES VALUES
@ -2819,7 +2821,8 @@ INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`)
(3, 9), (3, 9),
(4, 1), (4, 1),
(5, 9), (5, 9),
(6, 9); (6, 9),
(7, 9);
INSERT INTO `util`.`notificationQueue` (`id`, `notificationFk`, `params`, `authorFk`, `status`, `created`) INSERT INTO `util`.`notificationQueue` (`id`, `notificationFk`, `params`, `authorFk`, `status`, `created`)
VALUES VALUES
@ -2836,8 +2839,8 @@ INSERT INTO `util`.`notificationSubscription` (`notificationFk`, `userFk`)
(2, 1109), (2, 1109),
(1, 9), (1, 9),
(1, 3), (1, 3),
(6, 9); (6, 9),
(7, 9);
INSERT INTO `vn`.`routeConfig` (`id`, `defaultWorkCenterFk`) INSERT INTO `vn`.`routeConfig` (`id`, `defaultWorkCenterFk`)
VALUES VALUES
@ -2853,7 +2856,7 @@ INSERT INTO `vn`.`collection` (`id`, `created`, `workerFk`, `stateFk`, `itemPack
INSERT INTO `vn`.`itemConfig` (`id`, `isItemTagTriggerDisabled`, `monthToDeactivate`, `wasteRecipients`, `validPriorities`, `defaultPriority`, `defaultTag`, `warehouseFk`) INSERT INTO `vn`.`itemConfig` (`id`, `isItemTagTriggerDisabled`, `monthToDeactivate`, `wasteRecipients`, `validPriorities`, `defaultPriority`, `defaultTag`, `warehouseFk`)
VALUES VALUES
(0, 0, 24, '', '[1,2,3]', 2, 56, 60); (1, 0, 24, '', '[1,2,3]', 2, 56, 60);
INSERT INTO `vn`.`ticketCollection` (`ticketFk`, `collectionFk`, `created`, `level`, `wagon`, `smartTagFk`, `usedShelves`, `itemCount`, `liters`) INSERT INTO `vn`.`ticketCollection` (`ticketFk`, `collectionFk`, `created`, `level`, `wagon`, `smartTagFk`, `usedShelves`, `itemCount`, `liters`)
VALUES VALUES
@ -2890,7 +2893,7 @@ INSERT INTO `vn`.`ticketLog` (originFk, userFk, `action`, creationDate, changedM
(1, 18, 'insert', '1999-05-09 10:00:00', 'Ticket', 45, 'Super Man' , NULL, '{"id":45,"clientFk":8608,"warehouseFk":60,"shipped":"2023-05-16T22:00:00.000Z","nickname":"Super Man","addressFk":48637,"isSigned":true,"isLabeled":true,"isPrinted":true,"packages":0,"hour":0,"created":"2023-05-16T11:42:56.000Z","isBlocked":false,"hasPriority":false,"companyFk":442,"agencyModeFk":639,"landed":"2023-05-17T22:00:00.000Z","isBoxed":true,"isDeleted":true,"zoneFk":713,"zonePrice":13,"zoneBonus":0}', NULL); (1, 18, 'insert', '1999-05-09 10:00:00', 'Ticket', 45, 'Super Man' , NULL, '{"id":45,"clientFk":8608,"warehouseFk":60,"shipped":"2023-05-16T22:00:00.000Z","nickname":"Super Man","addressFk":48637,"isSigned":true,"isLabeled":true,"isPrinted":true,"packages":0,"hour":0,"created":"2023-05-16T11:42:56.000Z","isBlocked":false,"hasPriority":false,"companyFk":442,"agencyModeFk":639,"landed":"2023-05-17T22:00:00.000Z","isBoxed":true,"isDeleted":true,"zoneFk":713,"zonePrice":13,"zoneBonus":0}', NULL);
INSERT INTO `vn`.`osTicketConfig` (`id`, `host`, `user`, `password`, `oldStatus`, `newStatusId`, `day`, `comment`, `hostDb`, `userDb`, `passwordDb`, `portDb`, `responseType`, `fromEmailId`, `replyTo`) INSERT INTO `vn`.`osTicketConfig` (`id`, `host`, `user`, `password`, `oldStatus`, `newStatusId`, `day`, `comment`, `hostDb`, `userDb`, `passwordDb`, `portDb`, `responseType`, `fromEmailId`, `replyTo`)
VALUES VALUES
(0, 'http://localhost:56596/scp', 'ostadmin', 'Admin1', '1,6', 3, 60, 'Este CAU se ha cerrado automáticamente. Si el problema persiste responda a este mensaje.', 'localhost', 'osticket', 'osticket', 40003, 'reply', 1, 'all'); (1, 'http://localhost:56596/scp', 'ostadmin', 'Admin1', '1,6', 3, 60, 'Este CAU se ha cerrado automáticamente. Si el problema persiste responda a este mensaje.', 'localhost', 'osticket', 'osticket', 40003, 'reply', 1, 'all');
INSERT INTO `vn`.`mdbApp` (`app`, `baselineBranchFk`, `userFk`, `locked`) INSERT INTO `vn`.`mdbApp` (`app`, `baselineBranchFk`, `userFk`, `locked`)
VALUES VALUES
@ -3068,18 +3071,16 @@ INSERT INTO `vn`.`cmr` (id,truckPlate,observations,senderInstruccions,paymentIns
UPDATE vn.department UPDATE vn.department
SET workerFk = null; SET workerFk = null;
-- NEW WAREHOUSE
INSERT INTO vn.packaging INSERT INTO vn.packaging
VALUES('--', 2745600.00, 100.00, 120.00, 220.00, 0.00, 1, '2001-01-01 00:00:00.000', NULL, NULL, NULL, 0.00, 16, 0.00, 0, NULL, 0.00, NULL, NULL, 0, NULL, 0, 0); VALUES('--', 2745600.00, 100.00, 120.00, 220.00, 0.00, 1, '2001-01-01 00:00:00.000', NULL, NULL, NULL, 0.00, 16, 0.00, 0, NULL, 0.00, NULL, NULL, 0, NULL, 0, 0);
INSERT IGNORE INTO vn.intrastat INSERT IGNORE INTO vn.intrastat
SET id = 44219999, SET id = 44219999,
description = 'Manufacturas de madera', description = 'Manufacturas de madera',
taxClassFk = 1, taxClassFk = 1,
taxCodeFk = 1; taxCodeFk = 1;
INSERT IGNORE INTO vn.warehouse INSERT IGNORE INTO vn.warehouse
SET id = 999, SET id = 999,
name = 'TestingWarehouse', name = 'TestingWarehouse',
@ -3090,33 +3091,33 @@ INSERT IGNORE INTO vn.warehouse
hasProduction = TRUE; hasProduction = TRUE;
INSERT IGNORE INTO vn.sector INSERT IGNORE INTO vn.sector
SET id = 9991, SET id = 9991,
description = 'NormalSector', description = 'NormalSector',
warehouseFk = 999, warehouseFk = 999,
code = 'NS', code = 'NS',
isPackagingArea = FALSE, isPackagingArea = FALSE,
sonFk = NULL, sonFk = NULL,
isMain = TRUE, isMain = TRUE,
itemPackingTypeFk = NULL; itemPackingTypeFk = NULL;
INSERT IGNORE INTO vn.sector INSERT IGNORE INTO vn.sector
SET id = 9992, SET id = 9992,
description = 'PreviousSector', description = 'PreviousSector',
warehouseFk = 999, warehouseFk = 999,
code = 'PS', code = 'PS',
isPackagingArea = FALSE, isPackagingArea = FALSE,
sonFk = NULL, sonFk = NULL,
isMain = TRUE, isMain = TRUE,
itemPackingTypeFk = NULL; itemPackingTypeFk = NULL;
INSERT IGNORE INTO vn.sector INSERT IGNORE INTO vn.sector
SET id = 9993, SET id = 9993,
description = 'MezaninneSector', description = 'MezaninneSector',
warehouseFk = 999, warehouseFk = 999,
code = 'MS', code = 'MS',
isPackagingArea = FALSE, isPackagingArea = FALSE,
sonFk = 9991, sonFk = 9991,
isMain = TRUE, isMain = TRUE,
itemPackingTypeFk = NULL; itemPackingTypeFk = NULL;
@ -3150,58 +3151,58 @@ INSERT IGNORE INTO vn.itemType
SET id = 999, SET id = 999,
code = 'WOO', code = 'WOO',
name = 'Wood Objects', name = 'Wood Objects',
categoryFk = 3, categoryFk = 3,
workerFk = 103, workerFk = 103,
isInventory = TRUE, isInventory = TRUE,
life = 10, life = 10,
density = 250, density = 250,
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
temperatureFk = 'warm'; temperatureFk = 'warm';
INSERT IGNORE INTO vn.travel INSERT IGNORE INTO vn.travel
SET id = 99, SET id = 99,
shipped = CURDATE(), shipped = CURDATE(),
landed = CURDATE(), landed = CURDATE(),
warehouseInFk = 999, warehouseInFk = 999,
warehouseOutFk = 1, warehouseOutFk = 1,
isReceived = TRUE; isReceived = TRUE;
INSERT INTO vn.entry INSERT INTO vn.entry
SET id = 999, SET id = 999,
supplierFk = 791, supplierFk = 791,
isConfirmed = TRUE, isConfirmed = TRUE,
dated = CURDATE(), dated = CURDATE(),
travelFk = 99, travelFk = 99,
companyFk = 442; companyFk = 442;
INSERT INTO vn.ticket INSERT INTO vn.ticket
SET id = 999999, SET id = 999999,
clientFk = 2, clientFk = 2,
warehouseFk = 999, warehouseFk = 999,
shipped = CURDATE(), shipped = CURDATE(),
nickname = 'Cliente', nickname = 'Cliente',
addressFk = 1, addressFk = 1,
companyFk = 442, companyFk = 442,
agencyModeFk = 10, agencyModeFk = 10,
landed = CURDATE(); landed = CURDATE();
INSERT INTO vn.collection INSERT INTO vn.collection
SET id = 10101010, SET id = 10101010,
workerFk = 9; workerFk = 9;
INSERT IGNORE INTO vn.ticketCollection INSERT IGNORE INTO vn.ticketCollection
SET id = 10101010, SET id = 10101010,
ticketFk = 999999, ticketFk = 999999,
collectionFk = 10101010; collectionFk = 10101010;
INSERT INTO vn.item INSERT INTO vn.item
SET id = 999991, SET id = 999991,
name = 'Palito para pinchos', name = 'Palito para pinchos',
`size` = 25, `size` = 25,
stems = NULL, stems = NULL,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Palito para pinchos', longName = 'Palito para pinchos',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 6, weightByPiece = 6,
@ -3228,19 +3229,19 @@ INSERT INTO vn.sale
SET id = 99991, SET id = 99991,
itemFk = 999991, itemFk = 999991,
ticketFk = 999999, ticketFk = 999999,
concept = 'Palito para pinchos', concept = 'Palito para pinchos',
quantity = 3, quantity = 3,
price = 1, price = 1,
discount = 0; discount = 0;
INSERT INTO vn.item INSERT INTO vn.item
SET id = 999992, SET id = 999992,
name = 'Madera verde', name = 'Madera verde',
`size` = 10, `size` = 10,
stems = NULL, stems = NULL,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Madera verde', longName = 'Madera verde',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 50, weightByPiece = 50,
@ -3267,19 +3268,19 @@ INSERT INTO vn.sale
SET id = 99992, SET id = 99992,
itemFk = 999992, itemFk = 999992,
ticketFk = 999999, ticketFk = 999999,
concept = 'Madera Verde', concept = 'Madera Verde',
quantity = 10, quantity = 10,
price = 1, price = 1,
discount = 0; discount = 0;
INSERT INTO vn.item INSERT INTO vn.item
SET id = 999993, SET id = 999993,
name = 'Madera Roja/Morada', name = 'Madera Roja/Morada',
`size` = 12, `size` = 12,
stems = 2, stems = 2,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Madera Roja/Morada', longName = 'Madera Roja/Morada',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 35, weightByPiece = 35,
@ -3303,30 +3304,30 @@ INSERT INTO vn.buy
weight = 25; weight = 25;
INSERT INTO vn.itemShelving INSERT INTO vn.itemShelving
SET id = 9931, SET id = 9931,
itemFk = 999993, itemFk = 999993,
shelvingFk = 'NCC', shelvingFk = 'NCC',
visible = 10, visible = 10,
`grouping` = 5, `grouping` = 5,
packing = 10; packing = 10;
INSERT INTO vn.sale INSERT INTO vn.sale
SET id = 99993, SET id = 99993,
itemFk = 999993, itemFk = 999993,
ticketFk = 999999, ticketFk = 999999,
concept = 'Madera Roja/Morada', concept = 'Madera Roja/Morada',
quantity = 15, quantity = 15,
price = 1, price = 1,
discount = 0; discount = 0;
INSERT INTO vn.item INSERT INTO vn.item
SET id = 999994, SET id = 999994,
name = 'Madera Naranja', name = 'Madera Naranja',
`size` = 18, `size` = 18,
stems = 1, stems = 1,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Madera Naranja', longName = 'Madera Naranja',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 160, weightByPiece = 160,
@ -3353,19 +3354,19 @@ INSERT INTO vn.sale
SET id = 99994, SET id = 99994,
itemFk = 999994, itemFk = 999994,
ticketFk = 999999, ticketFk = 999999,
concept = 'Madera Naranja', concept = 'Madera Naranja',
quantity = 4, quantity = 4,
price = 1, price = 1,
discount = 0; discount = 0;
INSERT INTO vn.item INSERT INTO vn.item
SET id = 999995, SET id = 999995,
name = 'Madera Amarilla', name = 'Madera Amarilla',
`size` = 11, `size` = 11,
stems = 5, stems = 5,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Madera Amarilla', longName = 'Madera Amarilla',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 78, weightByPiece = 78,
@ -3392,20 +3393,20 @@ INSERT INTO vn.sale
SET id = 99995, SET id = 99995,
itemFk = 999995, itemFk = 999995,
ticketFk = 999999, ticketFk = 999999,
concept = 'Madera Amarilla', concept = 'Madera Amarilla',
quantity = 5, quantity = 5,
price = 1, price = 1,
discount = 0; discount = 0;
-- Palito naranja -- Palito naranja
INSERT INTO vn.item INSERT INTO vn.item
SET id = 999998, SET id = 999998,
name = 'Palito naranja', name = 'Palito naranja',
`size` = 11, `size` = 11,
stems = 1, stems = 1,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Palito naranja', longName = 'Palito naranja',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 78, weightByPiece = 78,
@ -3432,20 +3433,20 @@ INSERT INTO vn.sale
SET id = 99998, SET id = 99998,
itemFk = 999998, itemFk = 999998,
ticketFk = 999999, ticketFk = 999999,
concept = 'Palito naranja', concept = 'Palito naranja',
quantity = 60, quantity = 60,
price = 1, price = 1,
discount = 0; discount = 0;
-- Palito amarillo -- Palito amarillo
INSERT INTO vn.item INSERT INTO vn.item
SET id = 999999, SET id = 999999,
name = 'Palito amarillo', name = 'Palito amarillo',
`size` = 11, `size` = 11,
stems = 1, stems = 1,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Palito amarillo', longName = 'Palito amarillo',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 78, weightByPiece = 78,
@ -3472,20 +3473,20 @@ INSERT INTO vn.sale
SET id = 99999, SET id = 99999,
itemFk = 999999, itemFk = 999999,
ticketFk = 999999, ticketFk = 999999,
concept = 'Palito amarillo', concept = 'Palito amarillo',
quantity = 50, quantity = 50,
price = 1, price = 1,
discount = 0; discount = 0;
-- Palito azul -- Palito azul
INSERT INTO vn.item INSERT INTO vn.item
SET id = 1000000, SET id = 1000000,
name = 'Palito azul', name = 'Palito azul',
`size` = 10, `size` = 10,
stems = 1, stems = 1,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Palito azul', longName = 'Palito azul',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 78, weightByPiece = 78,
@ -3512,20 +3513,20 @@ INSERT INTO vn.sale
SET id = 100000, SET id = 100000,
itemFk = 1000000, itemFk = 1000000,
ticketFk = 999999, ticketFk = 999999,
concept = 'Palito azul', concept = 'Palito azul',
quantity = 50, quantity = 50,
price = 1, price = 1,
discount = 0; discount = 0;
-- Palito rojo -- Palito rojo
INSERT INTO vn.item INSERT INTO vn.item
SET id = 1000001, SET id = 1000001,
name = 'Palito rojo', name = 'Palito rojo',
`size` = 10, `size` = 10,
stems = NULL, stems = NULL,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Palito rojo', longName = 'Palito rojo',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 78, weightByPiece = 78,
@ -3553,20 +3554,20 @@ INSERT INTO vn.sale
SET id = 100001, SET id = 100001,
itemFk = 1000001, itemFk = 1000001,
ticketFk = 999999, ticketFk = 999999,
concept = 'Palito rojo', concept = 'Palito rojo',
quantity = 10, quantity = 10,
price = 1, price = 1,
discount = 0; discount = 0;
-- Previa -- Previa
INSERT IGNORE INTO vn.item INSERT IGNORE INTO vn.item
SET id = 999996, SET id = 999996,
name = 'Bolas de madera', name = 'Bolas de madera',
`size` = 2, `size` = 2,
stems = 4, stems = 4,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Bolas de madera', longName = 'Bolas de madera',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 20, weightByPiece = 20,
@ -3593,20 +3594,20 @@ INSERT vn.sale
SET id = 99996, SET id = 99996,
itemFk = 999996, itemFk = 999996,
ticketFk = 999999, ticketFk = 999999,
concept = 'Bolas de madera', concept = 'Bolas de madera',
quantity = 4, quantity = 4,
price = 7, price = 7,
discount = 0, discount = 0,
isPicked = TRUE; isPicked = TRUE;
INSERT IGNORE INTO vn.item INSERT IGNORE INTO vn.item
SET id = 999997, SET id = 999997,
name = 'Palitos de polo MIX', name = 'Palitos de polo MIX',
`size` = 14, `size` = 14,
stems = NULL, stems = NULL,
category = 'EXT', category = 'EXT',
typeFk = 999, typeFk = 999,
longName = 'Palitos de polo MIX', longName = 'Palitos de polo MIX',
itemPackingTypeFk = NULL, itemPackingTypeFk = NULL,
originFk = 1, originFk = 1,
weightByPiece = 20, weightByPiece = 20,
@ -3633,9 +3634,9 @@ INSERT vn.sale
SET id = 99997, SET id = 99997,
itemFk = 999997, itemFk = 999997,
ticketFk = 999999, ticketFk = 999999,
concept = 'Palitos de polo MIX', concept = 'Palitos de polo MIX',
quantity = 5, quantity = 5,
price = 7, price = 7,
discount = 0; discount = 0;
USE vn; USE vn;
@ -3668,38 +3669,38 @@ VALUES
-- Previous for Bolas de madera -- Previous for Bolas de madera
INSERT IGNORE INTO vn.sectorCollection INSERT IGNORE INTO vn.sectorCollection
SET id = 99, SET id = 99,
userFk = 1, userFk = 1,
sectorFk = 9992; sectorFk = 9992;
INSERT IGNORE INTO vn.saleGroup INSERT IGNORE INTO vn.saleGroup
SET id = 4, SET id = 4,
userFk = 1, userFk = 1,
parkingFk = 9, parkingFk = 9,
sectorFk = 9992; sectorFk = 9992;
INSERT IGNORE INTO vn.sectorCollectionSaleGroup INSERT IGNORE INTO vn.sectorCollectionSaleGroup
SET id = 9999, SET id = 9999,
sectorCollectionFk = 99, sectorCollectionFk = 99,
saleGroupFk = 999; saleGroupFk = 999;
INSERT vn.saleGroupDetail INSERT vn.saleGroupDetail
SET id = 99991, SET id = 99991,
saleFk = 99996, saleFk = 99996,
saleGroupFk = 999; saleGroupFk = 999;
INSERT INTO vn.saleTracking INSERT INTO vn.saleTracking
SET id = 7, SET id = 7,
saleFk = 99996, saleFk = 99996,
isChecked = TRUE, isChecked = TRUE,
workerFk = 103, workerFk = 103,
stateFk = 28; stateFk = 28;
INSERT IGNORE INTO vn.itemShelvingSale INSERT IGNORE INTO vn.itemShelvingSale
SET id = 991, SET id = 991,
itemShelvingFk = 9962, itemShelvingFk = 9962,
saleFk = 99996, saleFk = 99996,
quantity = 5, quantity = 5,
userFk = 1; userFk = 1;
UPDATE vn.ticket UPDATE vn.ticket
@ -3713,8 +3714,8 @@ UPDATE vn.collection
UPDATE vn.sale UPDATE vn.sale
SET isPicked =FALSE; SET isPicked =FALSE;
INSERT INTO vn.machineWorkerConfig(maxHours) INSERT INTO vn.machineWorkerConfig(id, maxHours)
VALUES(12); VALUES(1, 12);
INSERT INTO vn.workerAppTester(workerFk) VALUES(66); INSERT INTO vn.workerAppTester(workerFk) VALUES(66);
@ -3732,4 +3733,7 @@ UPDATE vn.saleTracking SET stateFk = 26 WHERE id = 5;
INSERT INTO vn.report (name) VALUES ('LabelCollection'); INSERT INTO vn.report (name) VALUES ('LabelCollection');
INSERT INTO vn.parkingLog(originFk, userFk, `action`, creationDate, description, changedModel,oldInstance, newInstance, changedModelId, changedModelValue) INSERT INTO vn.parkingLog(originFk, userFk, `action`, creationDate, description, changedModel,oldInstance, newInstance, changedModelId, changedModelValue)
VALUES(1, 18, 'update', util.VN_CURDATE(), NULL, 'SaleGroup', '{"parkingFk":null}', '{"parkingFk":1}', 1, NULL); VALUES(1, 18, 'update', util.VN_CURDATE(), NULL, 'SaleGroup', '{"parkingFk":null}', '{"parkingFk":1}', 1, NULL);
INSERT INTO vn.ticketLog (originFk,userFk,`action`,creationDate,changedModel,newInstance,changedModelId,changedModelValue)
VALUES (18,9,'insert','2001-01-01 11:01:00.000','Ticket','{"isDeleted":true}',45,'Super Man');

View File

@ -3,10 +3,11 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `sage`.`invoiceIn_add`(vI
BEGIN BEGIN
/** /**
* Traslada la info de contabilidad relacionada con las facturas recibidas * Traslada la info de contabilidad relacionada con las facturas recibidas
* *
* @vInvoiceInFk Factura recibida * @vInvoiceInFk Factura recibida
* @vXDiarioFk Id tabla XDiario * @vXDiarioFk Id tabla XDiario
*/ */
DECLARE vInvoiceInOriginalFk INT;
DECLARE vDone BOOL DEFAULT FALSE; DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vBase DOUBLE; DECLARE vBase DOUBLE;
DECLARE vVat DOUBLE; DECLARE vVat DOUBLE;
@ -23,25 +24,25 @@ BEGIN
DECLARE vInvoiceTypeInformative VARCHAR(1); DECLARE vInvoiceTypeInformative VARCHAR(1);
DECLARE vIsInformativeExportation BOOL DEFAULT FALSE; DECLARE vIsInformativeExportation BOOL DEFAULT FALSE;
DECLARE vCursor CURSOR FOR DECLARE vCursor CURSOR FOR
SELECT it.taxableBase, SELECT it.taxableBase,
CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)), CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)),
t.PorcentajeIva, t.PorcentajeIva,
it.transactionTypeSageFk, it.transactionTypeSageFk,
it.taxTypeSageFk, it.taxTypeSageFk,
tty.isIntracommunity, tty.isIntracommunity,
tt.ClaveOperacionDefecto tt.ClaveOperacionDefecto
FROM vn.invoiceIn i FROM vn.invoiceIn i
JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id
JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk
JOIN taxType tty ON tty.id = t.CodigoIva JOIN taxType tty ON tty.id = t.CodigoIva
JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk
LEFT JOIN vn.dua d ON d.id = vInvoiceInFk LEFT JOIN vn.dua d ON d.id = vInvoiceInFk
WHERE i.id = vInvoiceInFk WHERE i.id = vInvoiceInFk
AND d.id IS NULL; AND d.id IS NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DELETE FROM movContaIVA DELETE FROM movContaIVA
WHERE id = vXDiarioFk; WHERE id = vXDiarioFk;
@ -64,22 +65,22 @@ BEGIN
vTaxCode, vTaxCode,
vIsIntracommunity, vIsIntracommunity,
vOperationCode; vOperationCode;
IF vDone THEN IF vDone THEN
LEAVE l; LEAVE l;
END IF; END IF;
SET vTransactionCodeOld = vTransactionCode; SET vTransactionCodeOld = vTransactionCode;
SET vTaxCodeOld = vTaxCode; SET vTaxCodeOld = vTaxCode;
IF vOperationCode IS NOT NULL THEN IF vOperationCode IS NOT NULL THEN
UPDATE movContaIVA UPDATE movContaIVA
SET ClaveOperacionFactura = vOperationCode SET ClaveOperacionFactura = vOperationCode
WHERE id = vXDiarioFk; WHERE id = vXDiarioFk;
END IF; END IF;
SET vCounter = vCounter + 1; SET vCounter = vCounter + 1;
CASE vCounter CASE vCounter
WHEN 1 THEN WHEN 1 THEN
UPDATE movContaIVA UPDATE movContaIVA
SET BaseIva1 = vBase, SET BaseIva1 = vBase,
@ -115,31 +116,31 @@ BEGIN
WHERE id = vXDiarioFk; WHERE id = vXDiarioFk;
ELSE ELSE
SELECT vXDiarioFk INTO vXDiarioFk; SELECT vXDiarioFk INTO vXDiarioFk;
END CASE; END CASE;
IF vIsIntracommunity THEN IF vIsIntracommunity THEN
UPDATE movContaIVA UPDATE movContaIVA
SET Intracomunitaria = TRUE SET Intracomunitaria = TRUE
WHERE id = vXDiarioFk; WHERE id = vXDiarioFk;
END IF; END IF;
SET vTransactionCodeOld = vTransactionCode; SET vTransactionCodeOld = vTransactionCode;
SET vTaxCodeOld = vTaxCode; SET vTaxCodeOld = vTaxCode;
END LOOP; END LOOP;
CLOSE vCursor; CLOSE vCursor;
SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation
FROM vn.dua d FROM vn.dua d
LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN
AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci
WHERE d.ASIEN = ( WHERE d.ASIEN = (
SELECT ASIEN SELECT ASIEN
FROM vn.XDiario FROM vn.XDiario
WHERE id = vXDiarioFk) WHERE id = vXDiarioFk)
LIMIT 1; LIMIT 1;
UPDATE movContaIVA mci UPDATE movContaIVA mci
JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk
JOIN vn.XDiario x ON x.id = mci.id JOIN vn.XDiario x ON x.id = mci.id
@ -151,13 +152,13 @@ BEGIN
mci.Serie = ii.serial, mci.Serie = ii.serial,
mci.Factura = ii.id, mci.Factura = ii.id,
mci.FechaFactura = ii.issued, mci.FechaFactura = ii.issued,
mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) +
IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) +
IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) +
IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0), IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0),
mci.TipoFactura = IF(id.id, mci.TipoFactura = IF(id.id,
IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative),
IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)), IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)),
mci.CodigoCuentaFactura = x.SUBCTA, mci.CodigoCuentaFactura = x.SUBCTA,
mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif), mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif),
mci.Nombre = s.name, mci.Nombre = s.name,
@ -185,7 +186,7 @@ BEGIN
JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase
FROM vn.XDiario x1 FROM vn.XDiario x1
JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN
WHERE x2.BASEEURO <> 0 WHERE x2.BASEEURO <> 0
AND x1.id = vXDiarioFk AND x1.id = vXDiarioFk
)sub )sub
JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio' JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio'
@ -193,10 +194,41 @@ BEGIN
mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura), mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura),
mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase), mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase),
mci.PorRetencion = t.PorcentajeRetencion, mci.PorRetencion = t.PorcentajeRetencion,
mci.ImporteRetencion = iit.taxableBase * - 1 mci.ImporteRetencion = iit.taxableBase * - 1
WHERE mci.id = vXDiarioFk WHERE mci.id = vXDiarioFk
AND e.name = 'Retenciones' AND e.name = 'Retenciones'
AND id.id IS NULL; AND id.id IS NULL;
SELECT correctedFk INTO vInvoiceInOriginalFk
FROM vn.invoiceInCorrection
WHERE correctingFk = vInvoiceInFk;
IF vInvoiceInOriginalFk THEN
UPDATE movContaIVA mci
JOIN vn.invoiceInRefund iir ON iir.invoiceInRefundFk = vInvoiceInFk
JOIN (SELECT issued,
SUM(sub.taxableBase) taxableBase,
SUM(ROUND((sub.taxableBase * sub.PorcentajeIva) / 100 , 2)) vat
FROM(SELECT issued,
SUM(iit.taxableBase) taxableBase,
ti.PorcentajeIva
FROM vn.invoiceIn i
JOIN vn.invoiceInTax iit ON iit.invoiceInFk = i.id
JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
WHERE i.id = vInvoiceInOriginalFk
GROUP BY ti.CodigoIva)sub
)invoiceInOriginal
JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa'
SET mci.TipoRectificativa = iir.refundCategoryFk,
mci.ClaseAbonoRectificativas = iir.refundType,
mci.FechaFacturaOriginal = invoiceInOriginal.issued,
mci.FechaOperacion = invoiceInOriginal.issued,
mci.BaseImponibleOriginal = invoiceInOriginal.taxableBase,
mci.CuotaIvaOriginal = invoiceInOriginal.vat,
mci.ClaveOperacionFactura = co.ClaveOperacionFactura_
WHERE mci.id = vXDiarioFk;
END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -17,13 +17,13 @@ BEGIN
e.id accountFk, e.id accountFk,
UCASE(e.name), UCASE(e.name),
'' ''
FROM expense e FROM vn.expense e
UNION UNION
SELECT company_getCode(vCompanyFk), SELECT company_getCode(vCompanyFk),
a.account, a.account,
UCASE(a.bank), UCASE(a.bank),
'' ''
FROM accounting a FROM vn.accounting a
WHERE a.isActive WHERE a.isActive
AND a.`account` AND a.`account`
UNION UNION

View File

@ -0,0 +1,28 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`travel_hasUniqueAwb`(
vSelf INT
)
RETURNS BOOL
READS SQL DATA
BEGIN
/**
* Comprueba que el travel pasado tiene un AWB lógico,
* no se pueden tener varios AWB asociados al mismo DUA
*
* @param vSelf Id del travel
*/
DECLARE vHasUniqueAwb BOOL DEFAULT TRUE;
SELECT NOT COUNT(t2.awbFk) INTO vHasUniqueAwb
FROM entry e
JOIN travel t ON t.id = e.travelFk
JOIN duaEntry de ON de.entryFk = e.id
JOIN duaEntry de2 ON de2.duaFk = de.duaFk
JOIN entry e2 ON e2.id = de2.entryFk
JOIN travel t2 ON t2.id = e2.travelFk
WHERE t.id = vSelf
AND t2.awbFk <> t.awbFk;
RETURN vHasUniqueAwb;
END$$
DELIMITER ;

View File

@ -37,7 +37,7 @@ BEGIN
LEFT JOIN origin o ON o.id = i.originFk LEFT JOIN origin o ON o.id = i.originFk
) ON it.id = i.typeFk ) ON it.id = i.typeFk
LEFT JOIN edi.ekt ek ON b.ektFk = ek.id LEFT JOIN edi.ekt ek ON b.ektFk = ek.id
WHERE (b.packagingFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; WHERE (b.packagingFk = "--" OR b.price2 = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO';
DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk;
CREATE TEMPORARY TABLE tmp.lastEntryOk CREATE TEMPORARY TABLE tmp.lastEntryOk
@ -94,11 +94,6 @@ BEGIN
JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
SET b.price2 = eo.price2 WHERE b.price2 = 0 ; SET b.price2 = eo.price2 WHERE b.price2 = 0 ;
UPDATE buy b
JOIN tmp.lastEntry lt ON lt.buyFk = b.id
JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
SET b.packing = eo.packing WHERE b.packing = 0;
UPDATE buy b UPDATE buy b
JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntry lt ON lt.buyFk = b.id
JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk

View File

@ -1,8 +1,11 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTaxMakeByDua`(vDuaFk INT) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTaxMakeByDua`(
vDuaFk INT
)
BEGIN BEGIN
/** /**
* Borra los valores de duaTax y sus vctos. y los vuelve a crear en base a la tabla duaEntry * Borra los valores de duaTax y sus vctos. y los vuelve a
* crear en base a la tabla duaEntry.
* *
* @param vDuaFk Id del dua a recalcular * @param vDuaFk Id del dua a recalcular
*/ */
@ -26,7 +29,7 @@ BEGIN
LEAVE l; LEAVE l;
END IF; END IF;
CALL vn2008.recibidaIvaInsert(vInvoiceInFk); CALL invoiceInTax_recalc(vInvoiceInFk);
CALL invoiceInDueDay_recalc(vInvoiceInFk); CALL invoiceInDueDay_recalc(vInvoiceInFk);
END LOOP; END LOOP;

View File

@ -0,0 +1,62 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTax_recalc`(
vInvoiceInFk INT
)
BEGIN
/**
* Recalcula y actualiza los impuestos de la factura
* usando la última tasa de cambio y detalles de compra.
*
* @param vInvoiceInFk Id de factura recibida
*/
DECLARE vRate DOUBLE DEFAULT 1;
DECLARE vDated DATE;
DECLARE vExpenseFk INT;
SELECT MAX(rr.dated) INTO vDated
FROM referenceRate rr
JOIN invoiceIn ii ON ii.id = vInvoiceInFk
WHERE rr.dated <= ii.issued
AND rr.currencyFk = ii.currencyFk;
IF vDated THEN
SELECT `value` INTO vRate
FROM referenceRate
WHERE dated = vDated;
END IF;
DELETE FROM invoiceInTax WHERE invoiceInFk = vInvoiceInFk;
SELECT id INTO vExpenseFk
FROM expense
WHERE code = 'extraCommGoodsAcquisition';
IF vExpenseFk IS NULL THEN
CALL util.throw('Expense extraCommGoodsAcquisition not exists');
END IF;
INSERT INTO invoiceInTax(
invoiceInFk,
taxableBase,
expenseFk,
foreignValue,
taxTypeSageFk,
transactionTypeSageFk
)
SELECT ii.id,
SUM(b.buyingValue * b.quantity) / vRate bi,
vExpenseFk,
IF(c.code = 'EUR', NULL, SUM(b.buyingValue * b.quantity)),
s.taxTypeSageFk,
s.transactionTypeSageFk
FROM invoiceIn ii
JOIN currency c ON c.id = ii.currencyFk
JOIN `entry` e ON e.invoiceInFk = ii.id
JOIN supplier s ON s.id = e.supplierFk
JOIN buy b ON b.entryFk = e.id
LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk
AND rr.dated = ii.issued
WHERE ii.id = vInvoiceInFk
HAVING bi IS NOT NULL;
END$$
DELIMITER ;

View File

@ -1,234 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `sage`.`invoiceIn_add`(vInvoiceInFk INT, vXDiarioFk INT)
BEGIN
/**
* Traslada la info de contabilidad relacionada con las facturas recibidas
*
* @vInvoiceInFk Factura recibida
* @vXDiarioFk Id tabla XDiario
*/
DECLARE vInvoiceInOriginalFk INT;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vBase DOUBLE;
DECLARE vVat DOUBLE;
DECLARE vRate DOUBLE;
DECLARE vTransactionCode INT;
DECLARE vCounter INT DEFAULT 0;
DECLARE vTransactionCodeOld INT;
DECLARE vTaxCode INT;
DECLARE vTaxCodeOld INT;
DECLARE vOperationCode VARCHAR(1);
DECLARE vIsIntracommunity BOOL DEFAULT FALSE;
DECLARE vSerialDua VARCHAR(1) DEFAULT 'D';
DECLARE vInvoiceTypeReceived VARCHAR(1);
DECLARE vInvoiceTypeInformative VARCHAR(1);
DECLARE vIsInformativeExportation BOOL DEFAULT FALSE;
DECLARE vCursor CURSOR FOR
SELECT it.taxableBase,
CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)),
t.PorcentajeIva,
it.transactionTypeSageFk,
it.taxTypeSageFk,
tty.isIntracommunity,
tt.ClaveOperacionDefecto
FROM vn.invoiceIn i
JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id
JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk
JOIN taxType tty ON tty.id = t.CodigoIva
JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk
LEFT JOIN vn.dua d ON d.id = vInvoiceInFk
WHERE i.id = vInvoiceInFk
AND d.id IS NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DELETE FROM movContaIVA
WHERE id = vXDiarioFk;
SELECT codeSage INTO vInvoiceTypeReceived
FROM invoiceType WHERE code ='received';
SELECT codeSage INTO vInvoiceTypeInformative
FROM invoiceType WHERE code ='informative';
INSERT INTO movContaIVA(id, LibreA1)
VALUES (vXDiarioFk, vInvoiceInFk);
OPEN vCursor;
l: LOOP
FETCH vCursor INTO vBase,
vVat,
vRate,
vTransactionCode,
vTaxCode,
vIsIntracommunity,
vOperationCode;
IF vDone THEN
LEAVE l;
END IF;
SET vTransactionCodeOld = vTransactionCode;
SET vTaxCodeOld = vTaxCode;
IF vOperationCode IS NOT NULL THEN
UPDATE movContaIVA
SET ClaveOperacionFactura = vOperationCode
WHERE id = vXDiarioFk;
END IF;
SET vCounter = vCounter + 1;
CASE vCounter
WHEN 1 THEN
UPDATE movContaIVA
SET BaseIva1 = vBase,
PorIva1 = vRate,
CuotaIva1 = vVat,
CodigoTransaccion1 = vTransactionCode,
CodigoIva1 = vTaxCode
WHERE id = vXDiarioFk;
WHEN 2 THEN
UPDATE movContaIVA
SET BaseIva2 = vBase,
PorIva2 = vRate,
CuotaIva2 = vVat,
CodigoTransaccion2 = vTransactionCode,
CodigoIva2 = vTaxCode
WHERE id = vXDiarioFk;
WHEN 3 THEN
UPDATE movContaIVA
SET BaseIva3 = vBase,
PorIva3 = vRate,
CuotaIva3 = vVat,
CodigoTransaccion3 = vTransactionCode,
CodigoIva3 = vTaxCode
WHERE id = vXDiarioFk;
WHEN 4 THEN
UPDATE movContaIVA
SET BaseIva4 = vBase,
PorIva4 = vRate,
CuotaIva4 = vVat,
CodigoTransaccion4 = vTransactionCode,
CodigoIva4 = vTaxCode
WHERE id = vXDiarioFk;
ELSE
SELECT vXDiarioFk INTO vXDiarioFk;
END CASE;
IF vIsIntracommunity THEN
UPDATE movContaIVA
SET Intracomunitaria = TRUE
WHERE id = vXDiarioFk;
END IF;
SET vTransactionCodeOld = vTransactionCode;
SET vTaxCodeOld = vTaxCode;
END LOOP;
CLOSE vCursor;
SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation
FROM vn.dua d
LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN
AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci
WHERE d.ASIEN = (
SELECT ASIEN
FROM vn.XDiario
WHERE id = vXDiarioFk)
LIMIT 1;
UPDATE movContaIVA mci
JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk
JOIN vn.XDiario x ON x.id = mci.id
LEFT JOIN tmp.invoiceDua id ON id.id = mci.id
JOIN vn.supplier s ON s.id = ii.supplierFk
JOIN Naciones n ON n.countryFk = s.countryFk
SET mci.CodigoDivisa = ii.currencyFk,
mci.Año = YEAR(ii.issued),
mci.Serie = ii.serial,
mci.Factura = ii.id,
mci.FechaFactura = ii.issued,
mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) +
IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) +
IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) +
IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0),
mci.TipoFactura = IF(id.id,
IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative),
IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)),
mci.CodigoCuentaFactura = x.SUBCTA,
mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif),
mci.Nombre = s.name,
mci.SiglaNacion = n.SiglaNacion,
mci.EjercicioFactura = YEAR(ii.issued),
mci.FechaOperacion = ii.issued,
mci.MantenerAsiento = TRUE,
mci.SuFacturaNo = ii.supplierRef,
mci.IvaDeducible1 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva1, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
mci.IvaDeducible2 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva2, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
mci.IvaDeducible3 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva3, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
mci.IvaDeducible4 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva4, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
mci.FechaFacturaOriginal = x.FECHA_EX
WHERE mci.id = vXDiarioFk;
-- RETENCIONES
UPDATE movContaIVA mci
JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk
JOIN vn.XDiario x ON x.id = mci.id
JOIN vn.supplier s ON s.id = supplierFk
JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id
JOIN vn.expense e ON e.id = iit.expenseFk
JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk
LEFT JOIN tmp.invoiceDua id ON id.id = mci.id
JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase
FROM vn.XDiario x1
JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN
WHERE x2.BASEEURO <> 0
AND x1.id = vXDiarioFk
)sub
JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio'
SET mci.CodigoRetencion = t.CodigoRetencion,
mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura),
mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase),
mci.PorRetencion = t.PorcentajeRetencion,
mci.ImporteRetencion = iit.taxableBase * - 1
WHERE mci.id = vXDiarioFk
AND e.name = 'Retenciones'
AND id.id IS NULL;
SELECT correctedFk INTO vInvoiceInOriginalFk
FROM vn.invoiceInCorrection
WHERE correctingFk = vInvoiceInFk;
IF vInvoiceInOriginalFk THEN
UPDATE movContaIVA mci
JOIN vn.invoiceInRefund iir ON iir.invoiceInRefundFk = vInvoiceInFk
JOIN (SELECT issued,
SUM(sub.taxableBase) taxableBase,
SUM(ROUND((sub.taxableBase * sub.PorcentajeIva) / 100 , 2)) vat
FROM(SELECT issued,
SUM(iit.taxableBase) taxableBase,
ti.PorcentajeIva
FROM vn.invoiceIn i
JOIN vn.invoiceInTax iit ON iit.invoiceInFk = i.id
JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
WHERE i.id = vInvoiceInOriginalFk
GROUP BY ti.CodigoIva)sub
)invoiceInOriginal
JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa'
SET mci.TipoRectificativa = iir.refundCategoryFk,
mci.ClaseAbonoRectificativas = iir.refundType,
mci.FechaFacturaOriginal = invoiceInOriginal.issued,
mci.FechaOperacion = invoiceInOriginal.issued,
mci.BaseImponibleOriginal = invoiceInOriginal.taxableBase,
mci.CuotaIvaOriginal = invoiceInOriginal.vat,
mci.ClaveOperacionFactura = co.ClaveOperacionFactura_
WHERE mci.id = vXDiarioFk;
END IF;
END$$
DELIMITER ;

View File

@ -19,93 +19,74 @@ BEGIN
DECLARE vTypeFk INT; DECLARE vTypeFk INT;
DECLARE vPriority INT DEFAULT 1; DECLARE vPriority INT DEFAULT 1;
DECLARE vTag1 VARCHAR(20) COLLATE 'utf8_unicode_ci';
DECLARE vTag5 VARCHAR(20) COLLATE 'utf8_unicode_ci';
DECLARE vTag6 VARCHAR(20) COLLATE 'utf8_unicode_ci';
DECLARE vTag7 VARCHAR(20) COLLATE 'utf8_unicode_ci';
DECLARE vTag8 VARCHAR(20) COLLATE 'utf8_unicode_ci';
DECLARE vValue1 VARCHAR(50) COLLATE 'utf8_unicode_ci';
DECLARE vValue5 VARCHAR(50) COLLATE 'utf8_unicode_ci';
DECLARE vValue6 VARCHAR(50) COLLATE 'utf8_unicode_ci';
DECLARE vValue7 VARCHAR(50) COLLATE 'utf8_unicode_ci';
DECLARE vValue8 VARCHAR(50) COLLATE 'utf8_unicode_ci';
SELECT typeFk,
tag5,
value5,
tag6,
value6,
tag7,
value7,
tag8,
value8,
t.name,
it.value
INTO vTypeFk,
vTag5,
vValue5,
vTag6,
vValue6,
vTag7,
vValue7,
vTag8,
vValue8,
vTag1,
vValue1
FROM item i
LEFT JOIN itemTag it ON it.itemFk = i.id
AND it.priority = vPriority
LEFT JOIN tag t ON t.id = it.tagFk
WHERE i.id = vSelf;
CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated); CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated);
WITH itemTags AS (
SELECT i.id,
typeFk,
tag5,
value5,
tag6,
value6,
tag7,
value7,
tag8,
value8,
t.name,
it.value
FROM vn.item i
LEFT JOIN vn.itemTag it ON it.itemFk = i.id
AND it.priority = vPriority
LEFT JOIN vn.tag t ON t.id = it.tagFk
WHERE i.id = vSelf
)
SELECT i.id itemFk, SELECT i.id itemFk,
i.longName, i.longName,
i.subName, i.subName,
i.tag5, i.tag5,
i.value5, i.value5,
(i.value5 <=> vValue5) match5, (i.value5 <=> its.value5) match5,
i.tag6, i.tag6,
i.value6, i.value6,
(i.value6 <=> vValue6) match6, (i.value6 <=> its.value6) match6,
i.tag7, i.tag7,
i.value7, i.value7,
(i.value7 <=> vValue7) match7, (i.value7 <=> its.value7) match7,
i.tag8, i.tag8,
i.value8, i.value8,
(i.value8 <=> vValue8) match8, (i.value8 <=> its.value8) match8,
a.available, a.available,
IFNULL(ip.counter, 0) `counter`, IFNULL(ip.counter, 0) `counter`,
IF(b.groupingMode = 1, b.grouping, b.packing) minQuantity, IF(b.groupingMode = 1, b.grouping, b.packing) minQuantity,
iss.visible located iss.visible located
FROM item i FROM vn.item i
STRAIGHT_JOIN cache.available a ON a.item_id = i.id JOIN cache.available a ON a.item_id = i.id
AND a.calc_id = vCalcFk AND a.calc_id = vCalcFk
LEFT JOIN itemProposal ip ON ip.mateFk = i.id LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id
AND ip.itemFk = vSelf AND ip.itemFk = vSelf
LEFT JOIN itemTag it ON it.itemFk = i.id LEFT JOIN vn.itemTag it ON it.itemFk = i.id
AND it.priority = vPriority AND it.priority = vPriority
LEFT JOIN tag t ON t.id = it.tagFk LEFT JOIN vn.tag t ON t.id = it.tagFk
LEFT JOIN cache.last_buy lb ON lb.item_id = i.id LEFT JOIN cache.last_buy lb ON lb.item_id = i.id
AND lb.warehouse_id = vWarehouseFk AND lb.warehouse_id = vWarehouseFk
LEFT JOIN buy b ON b.id = lb.buy_id LEFT JOIN vn.buy b ON b.id = lb.buy_id
LEFT JOIN itemShelvingStock iss ON iss.itemFk = i.id LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id
AND iss.warehouseFk = vWarehouseFk AND iss.warehouseFk = vWarehouseFk
JOIN itemTags its
WHERE a.available > 0 WHERE a.available > 0
AND IF(vShowType, i.typeFk = vTypeFk, TRUE) AND IF(vShowType, i.typeFk = its.typeFk, TRUE)
AND i.id <> vSelf AND i.id <> vSelf
ORDER BY `counter` DESC, ORDER BY `counter` DESC,
(t.name = vTag1) DESC, (t.name = its.name) DESC,
(it.value = vValue1) DESC, (it.value = its.value) DESC,
(i.tag5 = vTag5) DESC, (i.tag5 = its.tag5) DESC,
match5 DESC, match5 DESC,
(i.tag6 = vTag6) DESC, (i.tag6 = its.tag6) DESC,
match6 DESC, match6 DESC,
(i.tag7 = vTag7) DESC, (i.tag7 = its.tag7) DESC,
match7 DESC, match7 DESC,
(i.tag8 = vTag8) DESC, (i.tag8 = its.tag8) DESC,
match8 DESC; match8 DESC;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -1,8 +1,9 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_getCollisions`() CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_getCollisions`()
BEGIN BEGIN
/** /**
* Calcula si para un mismo codigo postal y dia * Calcula si para un mismo codigo postal y dia
* hay mas de una zona configurada y manda correo * hay mas de una zona configurada y manda correo
* *
*/ */
@ -10,17 +11,18 @@ BEGIN
DECLARE vZoneFk INT; DECLARE vZoneFk INT;
DECLARE vIsDone INT DEFAULT FALSE; DECLARE vIsDone INT DEFAULT FALSE;
DECLARE vTableCollisions TEXT; DECLARE vTableCollisions TEXT;
DECLARE json_data JSON;
DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption; DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
DROP TEMPORARY TABLE IF EXISTS tmp.zone; DROP TEMPORARY TABLE IF EXISTS tmp.zone;
CREATE TEMPORARY TABLE tmp.zone CREATE TEMPORARY TABLE tmp.zone
SELECT z.id SELECT z.id
FROM zone z FROM zone z
JOIN agencyMode am ON am.id = z.agencyModeFk JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE dm.code IN ('AGENCY','DELIVERY'); WHERE dm.code IN ('AGENCY','DELIVERY');
CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE); CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE);
@ -35,7 +37,7 @@ BEGIN
PRIMARY KEY zoneFkk (zoneFk, geoFk), PRIMARY KEY zoneFkk (zoneFk, geoFk),
INDEX(geoFk)) INDEX(geoFk))
ENGINE = MyISAM; ENGINE = MyISAM;
OPEN cur1; OPEN cur1;
cur1Loop: LOOP cur1Loop: LOOP
SET vIsDone = FALSE; SET vIsDone = FALSE;
@ -43,82 +45,63 @@ BEGIN
IF vIsDone THEN IF vIsDone THEN
LEAVE cur1Loop; LEAVE cur1Loop;
END IF; END IF;
CALL zone_getLeaves(vZoneFk, NULL, NULL, TRUE); CALL zone_getLeaves(vZoneFk, NULL, NULL, TRUE);
myLoop: LOOP myLoop: LOOP
SET vGeoFk = NULL; SET vGeoFk = NULL;
SELECT geoFk INTO vGeoFk SELECT geoFk INTO vGeoFk
FROM tmp.zoneNodes zn FROM tmp.zoneNodes zn
WHERE NOT isChecked WHERE NOT isChecked
LIMIT 1; LIMIT 1;
IF vGeoFk IS NULL THEN IF vGeoFk IS NULL THEN
LEAVE myLoop; LEAVE myLoop;
END IF; END IF;
CALL zone_getLeaves(vZoneFk, vGeoFk, NULL, TRUE); CALL zone_getLeaves(vZoneFk, vGeoFk, NULL, TRUE);
UPDATE tmp.zoneNodes UPDATE tmp.zoneNodes
SET isChecked = TRUE SET isChecked = TRUE
WHERE geoFk = vGeoFk; WHERE geoFk = vGeoFk;
END LOOP; END LOOP;
END LOOP; END LOOP;
CLOSE cur1; CLOSE cur1;
DELETE FROM tmp.zoneNodes DELETE FROM tmp.zoneNodes
WHERE sons > 0; WHERE sons > 0;
DROP TEMPORARY TABLE IF EXISTS geoCollision; DROP TEMPORARY TABLE IF EXISTS geoCollision;
CREATE TEMPORARY TABLE geoCollision CREATE TEMPORARY TABLE geoCollision
SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk
FROM tmp.zoneNodes zn FROM tmp.zoneNodes zn
JOIN zone z ON z.id = zn.zoneFk JOIN zone z ON z.id = zn.zoneFk
JOIN zoneWarehouse zw ON z.id = zw.zoneFk JOIN zoneWarehouse zw ON z.id = zw.zoneFk
GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk
HAVING count(*) > 1; HAVING count(*) > 1;
SELECT '<table cellspacing="10"> -- Recojo los datos de la zona que ha dado conflicto
<tr> SELECT JSON_ARRAYAGG(
<th>C.Postal</th> JSON_OBJECT(
<th>Número de zona</th> 'zoneFk', zoneFk,
<th>Precio</th> 'zn', JSON_OBJECT('name', zn.name),
<th>Zona</th> 'z', JSON_OBJECT('name', z.name,'price', z.price),
<th>Almacén</th> 'w', JSON_OBJECT('name', w.name)
<th>Salix</th> )
</tr>' INTO vTableCollisions; ) FROM tmp.zoneNodes zn
JOIN zone z ON z.id = zn.zoneFk
INSERT INTO mail (receiver,replyTo,subject,body) JOIN geoCollision gc ON gc.agencyModeFk = z.agencyModeFk AND zn.geoFk = gc.geoFk
SELECT 'pepe@verdnatura.es' receiver, JOIN warehouse w ON w.id = gc.warehouseFk
'noreply@verdnatura.es' replyTo, INTO json_data;
CONCAT('Colisiones en zonas ', util.VN_CURDATE()) subject,
CONCAT(vTableCollisions, -- Creo un registro de la notificacion 'zone-included' para reportar via email
GROUP_CONCAT(sub.td SEPARATOR ''), SELECT util.notification_send(
'</table>') body 'zone-included',
FROM(SELECT JSON_OBJECT('zoneCollisions',json_data),
CONCAT('<tr> account.myUser_getId()
<td>', zn.name, '</td> );
<td>', zoneFk,'</td>
<td>', z.price,'</td> DROP TEMPORARY TABLE
<td>', z.name,'</td> geoCollision,
<td>', w.name, '</td>
<td>', CONCAT('<a href="https://salix.verdnatura.es/#!/zone/',
zoneFk,
'/location?q=%7B%22search%22:%22',
zn.name,
'%22%7D">'
'https://salix.verdnatura.es/#!/zone/',
zoneFk,
'/location?q=%7B%22search%22:%22',
zn.name,
'%22%7D</a>'),'</td>
</tr>') td
FROM tmp.zoneNodes zn
JOIN zone z ON z.id = zn.zoneFk
JOIN geoCollision gc ON gc.agencyModeFk = z.agencyModeFk AND zn.geoFk = gc.geoFk
JOIN warehouse w ON w.id = gc.warehouseFk) sub;
DROP TEMPORARY TABLE
geoCollision,
tmp.zone, tmp.zone,
tmp.zoneNodes; tmp.zoneNodes;
END$$ END$$

View File

@ -9,6 +9,7 @@ trig: BEGIN
DECLARE vGroupingMode TINYINT; DECLARE vGroupingMode TINYINT;
DECLARE vGenericFk INT; DECLARE vGenericFk INT;
DECLARE vGenericInDate BOOL; DECLARE vGenericInDate BOOL;
DECLARE vBuyerFk INT;
IF @isModeInventory THEN IF @isModeInventory THEN
LEAVE trig; LEAVE trig;
@ -20,6 +21,13 @@ trig: BEGIN
SET NEW.editorFk = account.myUser_getId(); SET NEW.editorFk = account.myUser_getId();
SELECT it.workerFk INTO vBuyerFk
FROM item i
JOIN itemType it ON it.id = i.typeFk
WHERE i.id = NEW.itemFk;
SET NEW.buyerFk = vBuyerFk;
CALL buy_checkGrouping(NEW.`grouping`); CALL buy_checkGrouping(NEW.`grouping`);
SELECT t.warehouseInFk, t.landed SELECT t.warehouseInFk, t.landed

View File

@ -7,6 +7,7 @@ trig:BEGIN
DECLARE vGenericInDate BOOL; DECLARE vGenericInDate BOOL;
DECLARE vIsInventory BOOL; DECLARE vIsInventory BOOL;
DECLARE vDefaultEntry INT; DECLARE vDefaultEntry INT;
DECLARE vBuyerFk INT;
IF @isTriggerDisabled THEN IF @isTriggerDisabled THEN
LEAVE trig; LEAVE trig;
@ -65,6 +66,15 @@ trig:BEGIN
SET NEW.isIgnored = TRUE; SET NEW.isIgnored = TRUE;
END IF; END IF;
IF NOT (NEW.itemFk <=> OLD.itemFk) THEN
SELECT it.workerFk INTO vBuyerFk
FROM item i
JOIN itemType it ON it.id = i.typeFk
WHERE i.id = NEW.itemFk;
SET NEW.buyerFk = vBuyerFk;
END IF;
IF NOT (NEW.itemFk <=> OLD.itemFk) OR IF NOT (NEW.itemFk <=> OLD.itemFk) OR
NOT (OLD.entryFk <=> NEW.entryFk) THEN NOT (OLD.entryFk <=> NEW.entryFk) THEN
CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck

View File

@ -7,6 +7,8 @@ BEGIN
CALL supplier_checkIsActive(NEW.supplierFk); CALL supplier_checkIsActive(NEW.supplierFk);
SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk);
SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk);
IF NEW.travelFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.travelFk) THEN
CALL util.throw('The travel is incorrect, there is a different AWB in the associated entries');
END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -8,13 +8,18 @@ BEGIN
DECLARE vHasDistinctWarehouses BOOL; DECLARE vHasDistinctWarehouses BOOL;
SET NEW.editorFk = account.myUser_getId(); SET NEW.editorFk = account.myUser_getId();
IF NOT (NEW.travelFk <=> OLD.travelFk) THEN
IF !(NEW.travelFk <=> OLD.travelFk) THEN IF NEW.travelFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.travelFk) THEN
CALL util.throw('The travel is incorrect, there is a different AWB in the associated entries');
END IF;
SELECT COUNT(*) > 0 INTO vIsVirtual SELECT COUNT(*) > 0 INTO vIsVirtual
FROM entryVirtual WHERE entryFk = NEW.id; FROM entryVirtual WHERE entryFk = NEW.id;
SELECT !(o.warehouseInFk <=> n.warehouseInFk) SELECT NOT (o.warehouseInFk <=> n.warehouseInFk)
OR !(o.warehouseOutFk <=> n.warehouseOutFk) OR NOT (o.warehouseOutFk <=> n.warehouseOutFk)
INTO vHasDistinctWarehouses INTO vHasDistinctWarehouses
FROM travel o, travel n FROM travel o, travel n
WHERE o.id = OLD.travelFk WHERE o.id = OLD.travelFk
@ -43,9 +48,8 @@ BEGIN
SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk);
END IF; END IF;
IF NOT (NEW.travelFk <=> OLD.travelFk) IF NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN
OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk, NEW.supplierFk);
SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk);
END IF; END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`travel_afterUpdate`
BEGIN BEGIN
CALL stock.log_add('travel', NEW.id, OLD.id); CALL stock.log_add('travel', NEW.id, OLD.id);
IF !(NEW.shipped <=> OLD.shipped) THEN IF NOT(NEW.shipped <=> OLD.shipped) THEN
UPDATE entry UPDATE entry
SET commission = entry_getCommission(travelFk, currencyFk,supplierFk) SET commission = entry_getCommission(travelFk, currencyFk,supplierFk)
WHERE travelFk = NEW.id; WHERE travelFk = NEW.id;
@ -23,5 +23,9 @@ BEGIN
CALL buy_checkItem(); CALL buy_checkItem();
END IF; END IF;
END IF; END IF;
IF (NOT(NEW.awbFk <=> OLD.awbFk)) AND NEW.awbFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.id) THEN
CALL util.throw('The AWB is incorrect, there is a different AWB in the associated entries');
END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -8,5 +8,9 @@ BEGIN
CALL travel_checkDates(NEW.shipped, NEW.landed); CALL travel_checkDates(NEW.shipped, NEW.landed);
CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk);
IF NEW.awbFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.id) THEN
CALL util.throw('The AWB is incorrect, there is a different AWB in the associated entries');
END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -8,5 +8,6 @@ BEGIN
`changedModel` = 'zoneIncluded', `changedModel` = 'zoneIncluded',
`changedModelId` = OLD.zoneFk, `changedModelId` = OLD.zoneFk,
`userFk` = account.myUser_getId(); `userFk` = account.myUser_getId();
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -4,5 +4,6 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`zoneIncluded_beforeIn
FOR EACH ROW FOR EACH ROW
BEGIN BEGIN
SET NEW.editorFk = account.myUser_getId(); SET NEW.editorFk = account.myUser_getId();
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -4,5 +4,6 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`zoneIncluded_beforeUp
FOR EACH ROW FOR EACH ROW
BEGIN BEGIN
SET NEW.editorFk = account.myUser_getId(); SET NEW.editorFk = account.myUser_getId();
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -1,25 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`ListaTicketsEncajados`(IN intId_Trabajador int)
BEGIN
SELECT Agencia,
Consignatario,
ti.Id_Ticket,
ts.userFk Id_Trabajador,
IFNULL(ncajas,0) AS ncajas,
IFNULL(nbultos,0) AS nbultos,
IFNULL(notros,0) AS notros,
ts.code AS Estado
FROM Tickets ti
INNER JOIN Consignatarios ON ti.Id_Consigna = Consignatarios.Id_consigna
INNER JOIN Agencias ON ti.Id_Agencia = Agencias.Id_Agencia
LEFT JOIN (SELECT ticketFk,count(*) AS ncajas FROM vn.expedition WHERE packagingFk=94 GROUP BY ticketFk) sub1 ON ti.Id_Ticket=sub1.ticketFk
LEFT JOIN (SELECT ticketFk,count(*) AS nbultos FROM vn.expedition WHERE packagingFk IS NULL GROUP BY ticketFk) sub2 ON ti.Id_Ticket=sub2.ticketFk
LEFT JOIN (SELECT ticketFk,count(*) AS notros FROM vn.expedition WHERE packagingFk >0 GROUP BY ticketFk) sub3 ON ti.Id_Ticket=sub3.ticketFk
INNER JOIN vn.ticketState ts ON ti.Id_ticket = ts.ticketFk
WHERE ti.Fecha=util.VN_CURDATE() AND
ts.userFk=intId_Trabajador
GROUP BY ti.Id_Ticket;
END$$
DELIMITER ;

View File

@ -1,49 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`customerDebtEvolution`(IN vCustomer INT)
BEGIN
SELECT * FROM
(
SELECT day, date, @s:= round(IFNULL(Euros,0) + @s,2) as Saldo, Euros, Credito, 0 as Cero
FROM
(
SELECT day, date, IFNULL(Euros,0) as Euros, Credito
FROM time
JOIN (SELECT @s:= 0, - Credito as Credito FROM Clientes WHERE Id_Cliente = vCustomer) c
LEFT JOIN
(SELECT Euros, date(Fecha) as Fecha FROM
(
SELECT Fechacobro as Fecha, Entregado as Euros
FROM Recibos
WHERE Id_Cliente = vCustomer
AND Fechacobro >= '2017-01-01'
UNION ALL
SELECT vn.getDueDate(io.issued,c.Vencimiento), - io.amount
FROM vn.invoiceOut io
JOIN Clientes c ON io.clientFk = c.Id_Cliente
WHERE io.clientFk = vCustomer
AND io.issued >= '2017-01-01'
UNION ALL
SELECT '2016-12-31', Debt
FROM bi.customerDebtInventory
WHERE Id_Cliente = vCustomer
UNION ALL
SELECT Fecha, - SUM(Cantidad * Preu * (100 - Descuento ) * 1.10 / 100)
FROM Tickets t
JOIN Movimientos m on m.Id_Ticket = t.Id_Ticket
WHERE Id_Cliente = vCustomer
AND Factura IS NULL
AND Fecha >= '2017-01-01'
GROUP BY Fecha
) sub2
ORDER BY Fecha
)sub ON time.date = sub.Fecha
WHERE time.date BETWEEN '2016-12-31' AND util.VN_CURDATE()
ORDER BY date
) sub3
)sub4
;
END$$
DELIMITER ;

View File

@ -1,22 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`preOrdenarRuta`(IN vRutaId INT)
BEGIN
/* Usa los valores del ultimo año para adivinar el orden de los tickets en la ruta
* vRutaId id ruta
* DEPRECATED use vn.routeGressPriority
*/
UPDATE Tickets mt
JOIN (
SELECT tt.Id_Consigna, round(ifnull(avg(t.Prioridad),0),0) as Prioridad
from Tickets t
JOIN Tickets tt on tt.Id_Consigna = t.Id_Consigna
where t.Fecha > TIMESTAMPADD(YEAR,-1,util.VN_CURDATE())
AND tt.Id_Ruta = vRutaId
GROUP BY Id_Consigna
) sub ON sub.Id_Consigna = mt.Id_Consigna
SET mt.Prioridad = sub.Prioridad
WHERE mt.Id_Ruta = vRutaId;
END$$
DELIMITER ;

View File

@ -1,22 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`prepare_ticket_list`(vStartingDate DATETIME, vEndingDate DATETIME)
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
CREATE TEMPORARY TABLE tmp.ticket_list
(PRIMARY KEY (Id_Ticket))
ENGINE = MEMORY
SELECT t.Id_Ticket, c.Id_Cliente
FROM Tickets t
LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.Id_Ticket
JOIN Clientes c ON c.Id_Cliente = t.Id_Cliente
WHERE c.typeFk IN ('normal','handMaking','internalUse')
AND (
Fecha BETWEEN util.today() AND vEndingDate
OR (
ts.alertLevel < 3
AND t.Fecha >= vStartingDate
AND t.Fecha < util.today()
)
);
END$$
DELIMITER ;

View File

@ -1,39 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`recibidaIvaInsert`(IN vId INT)
BEGIN
DECLARE vRate DOUBLE DEFAULT 1;
DECLARE vDated DATE;
SELECT MAX(rr.date) INTO vDated
FROM reference_rate rr
JOIN recibida r ON r.id = vId
WHERE rr.date <= r.fecha
AND rr.moneda_id = r.moneda_id ;
IF vDated THEN
SELECT rate INTO vRate
FROM reference_rate
WHERE `date` = vDated;
END IF;
DELETE FROM recibida_iva WHERE recibida_id = vId;
INSERT INTO recibida_iva(recibida_id, bi, gastos_id, divisa, taxTypeSageFk, transactionTypeSageFk)
SELECT r.id,
SUM(Costefijo * Cantidad) / IFNULL(vRate,1) bi,
6003000000,
IF(r.moneda_id = 1,NULL,SUM(Costefijo * Cantidad )) divisa,
taxTypeSageFk,
transactionTypeSageFk
FROM recibida r
JOIN Entradas e ON e.recibida_id = r.id
JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor
JOIN Compres c ON c.Id_Entrada = e.Id_Entrada
LEFT JOIN reference_rate rr ON rr.moneda_id = r.moneda_id AND rr.date = r.fecha
WHERE r.id = vId
HAVING bi IS NOT NULL;
END$$
DELIMITER ;

View File

@ -5,7 +5,6 @@ AS SELECT `c`.`id` AS `id`,
`c`.`code` AS `abbreviation`, `c`.`code` AS `abbreviation`,
`c`.`supplierAccountFk` AS `Id_Proveedores_account`, `c`.`supplierAccountFk` AS `Id_Proveedores_account`,
`c`.`workerManagerFk` AS `gerente_id`, `c`.`workerManagerFk` AS `gerente_id`,
`c`.`sage200Company` AS `digito_factura`,
`c`.`phytosanitary` AS `phytosanitary`, `c`.`phytosanitary` AS `phytosanitary`,
`c`.`companyCode` AS `CodigoEmpresa`, `c`.`companyCode` AS `CodigoEmpresa`,
`c`.`companyGroupFk` AS `empresa_grupo`, `c`.`companyGroupFk` AS `empresa_grupo`,

View File

@ -0,0 +1 @@
ALTER TABLE vn.buy ADD buyerFk int(10) unsigned DEFAULT NULL NULL;

View File

@ -0,0 +1 @@
ALTER TABLE util.notification MODIFY COLUMN id int(11) auto_increment NOT NULL;

View File

@ -0,0 +1,15 @@
INSERT IGNORE INTO util.notification ( `name`,`description`)
VALUES
( 'zone-included','An email to notify zoneCollisions');
-- Change value if destionation user should be different
SET @DESTINATION_USER = "pepe";
SET @MaxId = LAST_INSERT_ID();
INSERT IGNORE INTO util.notificationSubscription (notificationFk,userFk)
VALUES(
@MaxId, (SELECT id from `account`.`user` where name = @DESTINATION_USER));
INSERT IGNORE INTO util.notificationAcl (notificationFk,roleFk)
SELECT @MaxId, (SELECT role from `account`.`user` where name = @DESTINATION_USER) FROM util.notification WHERE name= "zone-included";

View File

@ -0,0 +1,19 @@
SET @isTriggerDisabled := TRUE;
UPDATE vn.buy
SET packing = 1
WHERE packing IS NULL
OR packing <= 0;
UPDATE vn.itemShelving
SET packing = 1
WHERE packing IS NULL
OR NOT packing;
SET @isTriggerDisabled := FALSE;
ALTER TABLE vn.buy MODIFY COLUMN packing int(11) NOT NULL DEFAULT 1 CHECK(packing > 0);
ALTER TABLE vn.itemShelving MODIFY COLUMN packing int(11) NOT NULL DEFAULT 1 CHECK(packing > 0);
-- Antes tenia '0=sin obligar 1=groping 2=packing' (groping → grouping)
ALTER TABLE vn.buy MODIFY COLUMN groupingMode tinyint(4) DEFAULT 0 NOT NULL COMMENT '0=sin obligar 1=grouping 2=packing';

View File

@ -0,0 +1,73 @@
-- Auto-generated SQL script #202403061303
UPDATE vn.company
SET companyCode=0
WHERE id=69;
UPDATE vn.company
SET companyCode=1
WHERE id=442;
UPDATE vn.company
SET companyCode=4
WHERE id=567;
UPDATE vn.company
SET companyCode=2
WHERE id=791;
UPDATE vn.company
SET companyCode=3
WHERE id=792;
UPDATE vn.company
SET companyCode=5
WHERE id=965;
UPDATE vn.company
SET companyCode=7
WHERE id=1381;
UPDATE vn.company
SET companyCode=3
WHERE id=1463;
UPDATE vn.company
SET companyCode=8
WHERE id=2142;
UPDATE vn.company
SET companyCode=6
WHERE id=2393;
UPDATE vn.company
SET companyCode=9
WHERE id=3869;
-- Auto-generated SQL script #202403061311
UPDATE vn.company
SET sage200Company=NULL
WHERE id=69;
UPDATE vn.company
SET sage200Company=NULL
WHERE id=442;
UPDATE vn.company
SET sage200Company=NULL
WHERE id=567;
UPDATE vn.company
SET sage200Company=NULL
WHERE id=791;
UPDATE vn.company
SET sage200Company=NULL
WHERE id=792;
UPDATE vn.company
SET sage200Company=NULL
WHERE id=965;
UPDATE vn.company
SET sage200Company=NULL
WHERE id=1381;
UPDATE vn.company
SET sage200Company=NULL
WHERE id=1463;
UPDATE vn.company
SET sage200Company=NULL
WHERE id=2142;
UPDATE vn.company
SET sage200Company=NULL
WHERE id=2393;
UPDATE vn.company
SET sage200Company=NULL
WHERE id=3869;
ALTER TABLE vn.company CHANGE sage200Company sage200Company__ int(2) DEFAULT NULL NULL COMMENT '@deprecated 06/03/2024';
ALTER TABLE vn.company MODIFY COLUMN sage200Company__ int(2) DEFAULT NULL NULL COMMENT '@deprecated 06/03/2024';

View File

@ -0,0 +1,36 @@
USE vn;
CREATE OR REPLACE TABLE vn.workerActivityType (
`code` varchar(20) NOT NULL,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
ALTER TABLE vn.department ADD workerActivityTypeFk varchar(20) NULL COMMENT 'Indica la actitividad que desempeña por defecto ese departamento';
ALTER TABLE vn.department ADD CONSTRAINT department_workerActivityType_FK FOREIGN KEY (workerActivityTypeFk) REFERENCES vn.workerActivityType(code) ON DELETE CASCADE ON UPDATE CASCADE;
INSERT INTO vn.workerActivityType (code, description) VALUES('ON_CHECKING', 'REVISION');
INSERT INTO vn.workerActivityType (code, description) VALUES('PREVIOUS_CAM', 'CAMARA');
INSERT INTO vn.workerActivityType (code, description) VALUES('PREVIOUS_ART', 'ARTIFICIAL');
INSERT INTO vn.workerActivityType (code, description) VALUES('ON_PREPARATION', 'SACADO');
INSERT INTO vn.workerActivityType (code, description) VALUES('PACKING', 'ENCAJADO');
INSERT INTO vn.workerActivityType (code, description) VALUES('FIELD', 'CAMPOS');
INSERT INTO vn.workerActivityType (code, description) VALUES('DELIVERY', 'REPARTO');
INSERT INTO vn.workerActivityType (code, description) VALUES('STORAGE', 'ALMACENAJE');
INSERT INTO vn.workerActivityType (code, description) VALUES('PALLETIZING', 'PALETIZADO');
INSERT INTO vn.workerActivityType (code, description) VALUES('STOP', 'PARADA');
INSERT INTO salix.ACL ( model, property, accessType, permission, principalType, principalId) VALUES('WorkerActivityType', '*', 'READ', 'ALLOW', 'ROLE', 'production');
INSERT INTO salix.ACL ( model, property, accessType, permission, principalType, principalId) VALUES('WorkerActivity', '*', '*', 'ALLOW', 'ROLE', 'production');
ALTER TABLE vn.workerActivity MODIFY COLUMN event enum('open','close','insert','delete','update','refresh') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NULL;
ALTER TABLE vn.workerActivity MODIFY COLUMN model enum('COM','ENT','TPV','ENC','LAB','ETI','APP') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL;
ALTER TABLE vn.workerActivity ADD workerActivityTypeFk varchar(20) NULL;
ALTER TABLE vn.workerActivity ADD CONSTRAINT workerActivity_workerActivityType_FK FOREIGN KEY (workerActivityTypeFk) REFERENCES vn.workerActivityType(code) ON DELETE CASCADE ON UPDATE CASCADE;

View File

@ -0,0 +1,3 @@
-- Place your SQL code here

View File

@ -0,0 +1,23 @@
-- account.accountConfig
ALTER TABLE account.accountConfig MODIFY COLUMN id tinyint(3) unsigned NOT NULL;
ALTER TABLE account.accountConfig ADD CONSTRAINT accountConfig_check CHECK (id = 1);
-- account.ldapConfig
ALTER TABLE account.ldapConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE account.ldapConfig ADD CONSTRAINT ldapConfig_check CHECK (id = 1);
-- account.mailConfig
ALTER TABLE account.mailConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE account.mailConfig ADD CONSTRAINT mailConfig_check CHECK (id = 1);
-- account.roleConfig
ALTER TABLE account.roleConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE account.roleConfig ADD CONSTRAINT roleConfig_check CHECK (id = 1);
-- account.sambaConfig
ALTER TABLE account.sambaConfig MODIFY COLUMN id tinyint(3) unsigned NOT NULL;
ALTER TABLE account.sambaConfig ADD CONSTRAINT sambaConfig_check CHECK (id = 1);
-- account.userConfig
ALTER TABLE account.userConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE account.userConfig ADD CONSTRAINT userConfig_check CHECK (id = 1);

View File

@ -0,0 +1,7 @@
-- bs.nightTaskConfig
ALTER TABLE bs.nightTaskConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE bs.nightTaskConfig ADD CONSTRAINT nightTaskConfig_check CHECK (id = 1);
-- bs.workerProductivityConfig
ALTER TABLE bs.workerProductivityConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE bs.workerProductivityConfig ADD CONSTRAINT workerProductivityConfig_check CHECK (id = 1);

View File

@ -0,0 +1,15 @@
-- edi.exchangeConfig
ALTER TABLE edi.exchangeConfig MODIFY COLUMN id tinyint(3) unsigned NOT NULL;
ALTER TABLE edi.exchangeConfig ADD CONSTRAINT exchangeConfig_check CHECK (id = 1);
-- edi.ftpConfig
ALTER TABLE edi.ftpConfig MODIFY COLUMN id tinyint(3) unsigned NOT NULL;
ALTER TABLE edi.ftpConfig ADD CONSTRAINT ftpConfig_check CHECK (id = 1);
-- edi.imapConfig (Tiene más de 1 registro en producción)
-- ALTER TABLE edi.imapConfig MODIFY COLUMN id tinyint(3) unsigned NOT NULL;
-- ALTER TABLE edi.imapConfig ADD CONSTRAINT imapConfig_check CHECK (id = 1);
-- edi.offerRefreshConfig
ALTER TABLE edi.offerRefreshConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE edi.offerRefreshConfig ADD CONSTRAINT offerRefreshConfig_check CHECK (id = 1);

View File

@ -0,0 +1,27 @@
-- hedera.config
ALTER TABLE hedera.config MODIFY COLUMN id tinyint(3) unsigned NOT NULL;
ALTER TABLE hedera.config ADD CONSTRAINT config_check CHECK (id = 1);
-- hedera.imageConfig
ALTER TABLE hedera.imageConfig MODIFY COLUMN id tinyint(3) unsigned NOT NULL;
ALTER TABLE hedera.imageConfig ADD CONSTRAINT imageConfig_check CHECK (id = 1);
-- hedera.mailConfig
ALTER TABLE hedera.mailConfig MODIFY COLUMN id tinyint(3) unsigned NOT NULL;
ALTER TABLE hedera.mailConfig ADD CONSTRAINT mailConfig_check CHECK (id = 1);
-- hedera.orderConfig
ALTER TABLE hedera.orderConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE hedera.orderConfig ADD CONSTRAINT orderConfig_check CHECK (id = 1);
-- hedera.shelfConfig (Tiene más de 1 registro en producción)
-- ALTER TABLE hedera.shelfConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
-- ALTER TABLE hedera.shelfConfig ADD CONSTRAINT shelfConfig_check CHECK (id = 1);
-- hedera.tpvConfig
ALTER TABLE hedera.tpvConfig MODIFY COLUMN id tinyint(3) unsigned NOT NULL;
ALTER TABLE hedera.tpvConfig ADD CONSTRAINT tpvConfig_check CHECK (id = 1);
-- hedera.tpvImapConfig
ALTER TABLE hedera.tpvImapConfig MODIFY COLUMN id tinyint(3) unsigned NOT NULL;
ALTER TABLE hedera.tpvImapConfig ADD CONSTRAINT tpvImapConfig_check CHECK (id = 1);

View File

@ -0,0 +1,15 @@
-- pbx.config
ALTER TABLE pbx.config MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE pbx.config ADD CONSTRAINT config_check CHECK (id = 1);
-- pbx.followmeConfig
ALTER TABLE pbx.followmeConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE pbx.followmeConfig ADD CONSTRAINT followmeConfig_check CHECK (id = 1);
-- pbx.queueConfig (Tiene más de 1 registro en producción)
-- ALTER TABLE pbx.queueConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
-- ALTER TABLE pbx.queueConfig ADD CONSTRAINT queueConfig_check CHECK (id = 1);
-- pbx.sipConfig
ALTER TABLE pbx.sipConfig MODIFY COLUMN id mediumint(8) unsigned NOT NULL;
ALTER TABLE pbx.sipConfig ADD CONSTRAINT sipConfig_check CHECK (id = 1);

View File

@ -0,0 +1,3 @@
-- sage.config
ALTER TABLE sage.config MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE sage.config ADD CONSTRAINT config_check CHECK (id = 1);

View File

@ -0,0 +1,7 @@
-- salix.accessTokenConfig
ALTER TABLE salix.accessTokenConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE salix.accessTokenConfig ADD CONSTRAINT accessTokenConfig_check CHECK (id = 1);
-- salix.printConfig
ALTER TABLE salix.printConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE salix.printConfig ADD CONSTRAINT printConfig_check CHECK (id = 1);

View File

@ -0,0 +1,3 @@
-- srt.config
ALTER TABLE srt.config MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE srt.config ADD CONSTRAINT config_check CHECK (id = 1);

View File

@ -0,0 +1,11 @@
-- util.config
ALTER TABLE util.config MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE util.config ADD CONSTRAINT config_check CHECK (id = 1);
-- util.notificationConfig
ALTER TABLE util.notificationConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE util.notificationConfig ADD CONSTRAINT notificationConfig_check CHECK (id = 1);
-- util.versionConfig
ALTER TABLE util.versionConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE util.versionConfig ADD CONSTRAINT versionConfig_check CHECK (id = 1);

View File

@ -0,0 +1,87 @@
-- vn.accountingConfig
ALTER TABLE vn.accountingConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.accountingConfig ADD CONSTRAINT accountingConfig_check CHECK (id = 1);
-- vn.auctionConfig
ALTER TABLE vn.auctionConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.auctionConfig ADD CONSTRAINT auctionConfig_check CHECK (id = 1);
-- vn.autoRadioConfig
ALTER TABLE vn.autoRadioConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.autoRadioConfig ADD CONSTRAINT autoRadioConfig_check CHECK (id = 1);
-- vn.bankEntityConfig
ALTER TABLE vn.bankEntityConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.bankEntityConfig ADD CONSTRAINT bankEntityConfig_check CHECK (id = 1);
-- vn.bionicConfig
ALTER TABLE vn.bionicConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.bionicConfig ADD CONSTRAINT bionicConfig_check CHECK (id = 1);
-- vn.buyConfig
ALTER TABLE vn.buyConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.buyConfig ADD CONSTRAINT buyConfig_check CHECK (id = 1);
-- vn.chatConfig
ALTER TABLE vn.chatConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.chatConfig ADD CONSTRAINT chatConfig_check CHECK (id = 1);
-- vn.claimConfig
ALTER TABLE vn.claimConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.claimConfig ADD CONSTRAINT claimConfig_check CHECK (id = 1);
-- vn.clientConfig
ALTER TABLE vn.clientConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.clientConfig ADD CONSTRAINT clientConfig_check CHECK (id = 1);
-- vn.comparativeAddConfig
ALTER TABLE vn.comparativeAddConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.comparativeAddConfig ADD CONSTRAINT comparativeAddConfig_check CHECK (id = 1);
-- vn.comparativeConfig
ALTER TABLE vn.comparativeConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.comparativeConfig ADD CONSTRAINT comparativeConfig_check CHECK (id = 1);
-- vn.config
ALTER TABLE vn.config MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.config ADD CONSTRAINT config_check CHECK (id = 1);
-- vn.conveyorConfig (Tiene más de 1 registro en producción)
-- ALTER TABLE vn.conveyorConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
-- ALTER TABLE vn.conveyorConfig ADD CONSTRAINT conveyorConfig_check CHECK (id = 1);
-- vn.deviceProductionConfig
ALTER TABLE vn.deviceProductionConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.deviceProductionConfig ADD CONSTRAINT deviceProductionConfig_check CHECK (id = 1);
-- vn.docuwareConfig
ALTER TABLE vn.docuwareConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.docuwareConfig ADD CONSTRAINT docuwareConfig_check CHECK (id = 1);
-- vn.floramondoConfig
ALTER TABLE vn.floramondoConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.floramondoConfig ADD CONSTRAINT floramondoConfig_check CHECK (id = 1);
-- vn.franceExpressConfig
ALTER TABLE vn.franceExpressConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.franceExpressConfig ADD CONSTRAINT franceExpressConfig_check CHECK (id = 1);
-- vn.glsConfig
ALTER TABLE vn.glsConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.glsConfig ADD CONSTRAINT glsConfig_check CHECK (id = 1);
-- vn.greugeConfig
ALTER TABLE vn.greugeConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.greugeConfig ADD CONSTRAINT greugeConfig_check CHECK (id = 1);
-- vn.inventoryConfig
ALTER TABLE vn.inventoryConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.inventoryConfig ADD CONSTRAINT inventoryConfig_check CHECK (id = 1);
-- vn.invoiceInConfig
ALTER TABLE vn.invoiceInConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.invoiceInConfig ADD CONSTRAINT invoiceInConfig_check CHECK (id = 1);
-- vn.invoiceOutConfig
ALTER TABLE vn.invoiceOutConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.invoiceOutConfig ADD CONSTRAINT invoiceOutConfig_check CHECK (id = 1);

View File

@ -0,0 +1,91 @@
-- vn.invoiceOutTaxConfig (Tiene más de 1 registro en producción)
-- ALTER TABLE vn.invoiceOutTaxConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
-- ALTER TABLE vn.invoiceOutTaxConfig ADD CONSTRAINT invoiceOutTaxConfig_check CHECK (id = 1);
-- vn.itemConfig
ALTER TABLE vn.itemConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.itemConfig ADD CONSTRAINT itemConfig_check CHECK (id = 1);
-- vn.machineWorkerConfig
ALTER TABLE vn.machineWorkerConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.machineWorkerConfig ADD CONSTRAINT machineWorkerConfig_check CHECK (id = 1);
-- vn.mdbConfig
ALTER TABLE vn.mdbConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.mdbConfig ADD CONSTRAINT mdbConfig_check CHECK (id = 1);
-- vn.mrwConfig
ALTER TABLE vn.mrwConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.mrwConfig ADD CONSTRAINT mrwConfig_check CHECK (id = 1);
-- vn.osTicketConfig
ALTER TABLE vn.osTicketConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.osTicketConfig ADD CONSTRAINT osTicketConfig_check CHECK (id = 1);
-- vn.packagingConfig
ALTER TABLE vn.packagingConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.packagingConfig ADD CONSTRAINT packagingConfig_check CHECK (id = 1);
-- vn.packingSiteConfig
ALTER TABLE vn.packingSiteConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.packingSiteConfig ADD CONSTRAINT packingSiteConfig_check CHECK (id = 1);
-- vn.productionConfig
ALTER TABLE vn.productionConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.productionConfig ADD CONSTRAINT productionConfig_check CHECK (id = 1);
-- vn.rateConfig
ALTER TABLE vn.rateConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.rateConfig ADD CONSTRAINT rateConfig_check CHECK (id = 1);
-- vn.routeConfig
ALTER TABLE vn.routeConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.routeConfig ADD CONSTRAINT routeConfig_check CHECK (id = 1);
-- vn.salespersonConfig
ALTER TABLE vn.salespersonConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.salespersonConfig ADD CONSTRAINT salespersonConfig_check CHECK (id = 1);
-- vn.sendingConfig
ALTER TABLE vn.sendingConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.sendingConfig ADD CONSTRAINT sendingConfig_check CHECK (id = 1);
-- vn.smsConfig
ALTER TABLE vn.smsConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.smsConfig ADD CONSTRAINT smsConfig_check CHECK (id = 1);
-- vn.ticketConfig
ALTER TABLE vn.ticketConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.ticketConfig ADD CONSTRAINT ticketConfig_check CHECK (id = 1);
-- vn.tillConfig
ALTER TABLE vn.tillConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.tillConfig ADD CONSTRAINT tillConfig_check CHECK (id = 1);
-- vn.travelConfig
ALTER TABLE vn.travelConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.travelConfig ADD CONSTRAINT travelConfig_check CHECK (id = 1);
-- vn.viaexpressConfig
ALTER TABLE vn.viaexpressConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.viaexpressConfig ADD CONSTRAINT viaexpressConfig_check CHECK (id = 1);
-- vn.wagonConfig
ALTER TABLE vn.wagonConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.wagonConfig ADD CONSTRAINT wagonConfig_check CHECK (id = 1);
-- vn.workerConfig
ALTER TABLE vn.workerConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.workerConfig ADD CONSTRAINT workerConfig_check CHECK (id = 1);
-- vn.workerTimeControlConfig
ALTER TABLE vn.workerTimeControlConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.workerTimeControlConfig ADD CONSTRAINT workerTimeControlConfig_check CHECK (id = 1);
-- vn.zipConfig
ALTER TABLE vn.zipConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.zipConfig ADD CONSTRAINT zipConfig_check CHECK (id = 1);
-- vn.zoneConfig
ALTER TABLE vn.zoneConfig MODIFY COLUMN id int(10) unsigned NOT NULL;
ALTER TABLE vn.zoneConfig ADD CONSTRAINT zoneConfig_check CHECK (id = 1);

View File

@ -0,0 +1 @@
ALTER TABLE util.debug MODIFY COLUMN value text CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL;

View File

@ -24,7 +24,7 @@ describe('Ticket descriptor path', () => {
it('should go back to the ticket index then search and access a ticket summary', async() => { it('should go back to the ticket index then search and access a ticket summary', async() => {
await page.accessToSection('ticket.index'); await page.accessToSection('ticket.index');
await page.accessToSearchResult('11'); await page.accessToSearchResult('33');
}); });
it('should add the ticket to thursday turn using the descriptor more menu', async() => { it('should add the ticket to thursday turn using the descriptor more menu', async() => {
@ -33,7 +33,7 @@ describe('Ticket descriptor path', () => {
await page.waitToClick(selectors.ticketDescriptor.thursdayButton); await page.waitToClick(selectors.ticketDescriptor.thursdayButton);
const message = await page.waitForSnackbar(); const message = await page.waitForSnackbar();
expect(message.text).toContain('Data saved!'); expect(message.text).toContain('Current ticket deleted and added to shift');
}); });
it('should again click on the Tickets button of the top bar menu', async() => { it('should again click on the Tickets button of the top bar menu', async() => {
@ -43,7 +43,7 @@ describe('Ticket descriptor path', () => {
await page.waitForState('ticket.index'); await page.waitForState('ticket.index');
}); });
it('should confirm the ticket 11 was added to thursday', async() => { it('should confirm the ticket 33 was added to thursday', async() => {
await page.accessToSection('ticket.weekly.index'); await page.accessToSection('ticket.weekly.index');
const result = await page.waitToGetProperty(selectors.ticketsIndex.thirdWeeklyTicket, 'value'); const result = await page.waitToGetProperty(selectors.ticketsIndex.thirdWeeklyTicket, 'value');
@ -57,8 +57,8 @@ describe('Ticket descriptor path', () => {
await page.waitForState('ticket.index'); await page.waitForState('ticket.index');
}); });
it('should now search for the ticket 11', async() => { it('should now search for the ticket 33', async() => {
await page.accessToSearchResult('11'); await page.accessToSearchResult('33');
await page.waitForState('ticket.card.summary'); await page.waitForState('ticket.card.summary');
}); });
@ -68,7 +68,7 @@ describe('Ticket descriptor path', () => {
await page.waitToClick(selectors.ticketDescriptor.saturdayButton); await page.waitToClick(selectors.ticketDescriptor.saturdayButton);
const message = await page.waitForSnackbar(); const message = await page.waitForSnackbar();
expect(message.text).toContain('Data saved!'); expect(message.text).toContain('Current ticket deleted and added to shift');
}); });
it('should click on the Tickets button of the top bar menu once again', async() => { it('should click on the Tickets button of the top bar menu once again', async() => {
@ -78,7 +78,7 @@ describe('Ticket descriptor path', () => {
await page.waitForState('ticket.index'); await page.waitForState('ticket.index');
}); });
it('should confirm the ticket 11 was added on saturday', async() => { it('should confirm the ticket 33 was added on saturday', async() => {
await page.accessToSection('ticket.weekly.index'); await page.accessToSection('ticket.weekly.index');
await page.waitForTimeout(5000); await page.waitForTimeout(5000);
@ -87,14 +87,14 @@ describe('Ticket descriptor path', () => {
expect(result).toEqual('Saturday'); expect(result).toEqual('Saturday');
}); });
it('should now search for the weekly ticket 11', async() => { it('should now search for the weekly ticket 33', async() => {
await page.doSearch('11'); await page.doSearch('33');
const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult); const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult);
expect(nResults).toEqual(2); expect(nResults).toEqual(2);
}); });
it('should delete the weekly ticket 11', async() => { it('should delete the weekly ticket 33', async() => {
await page.waitToClick(selectors.ticketsIndex.firstWeeklyTicketDeleteIcon); await page.waitToClick(selectors.ticketsIndex.firstWeeklyTicketDeleteIcon);
await page.waitToClick(selectors.ticketsIndex.acceptDeleteTurn); await page.waitToClick(selectors.ticketsIndex.acceptDeleteTurn);
const message = await page.waitForSnackbar(); const message = await page.waitForSnackbar();

View File

@ -83,22 +83,27 @@ export default class Auth {
} }
onLoginOk(json, now, remember) { onLoginOk(json, now, remember) {
this.vnToken.set(json.data.token, now, json.data.ttl, remember); return this.$http.get('VnUsers/ShareToken', {
headers: {Authorization: json.data.token}
return this.loadAcls().then(() => { }).then(({data}) => {
let continueHash = this.$state.params.continue; this.vnToken.set(json.data.token, data.multimediaToken.id, now, json.data.ttl, remember);
if (continueHash) this.loadAcls().then(() => {
this.$window.location = continueHash; let continueHash = this.$state.params.continue;
else if (continueHash)
this.$state.go('home'); this.$window.location = continueHash;
}); else
this.$state.go('home');
});
}).catch(() => {});
} }
logout() { logout() {
this.$http.post('Accounts/logout', null, {headers: {'Authorization': this.vnToken.tokenMultimedia},
}).catch(() => {});
let promise = this.$http.post('VnUsers/logout', null, { let promise = this.$http.post('VnUsers/logout', null, {
headers: {Authorization: this.vnToken.token} headers: {Authorization: this.vnToken.token}
}).catch(() => {}); }).catch(() => {});
this.vnToken.unset(); this.vnToken.unset();
this.loggedIn = false; this.loggedIn = false;
this.vnModules.reset(); this.vnModules.reset();

View File

@ -19,7 +19,7 @@ function interceptor($q, vnApp, $translate) {
if (config.url.charAt(0) !== '/' && apiPath) if (config.url.charAt(0) !== '/' && apiPath)
config.url = `${apiPath}${config.url}`; config.url = `${apiPath}${config.url}`;
if (token) if (token && !config.headers.Authorization)
config.headers.Authorization = token; config.headers.Authorization = token;
if ($translate.use()) if ($translate.use())
config.headers['Accept-Language'] = $translate.use(); config.headers['Accept-Language'] = $translate.use();

View File

@ -24,21 +24,22 @@ export default class Token {
} catch (e) {} } catch (e) {}
} }
set(token, created, ttl, remember) { set(token, tokenMultimedia, created, ttl, remember) {
this.unset(); this.unset();
Object.assign(this, { Object.assign(this, {
token, token,
tokenMultimedia,
created, created,
ttl, ttl,
remember remember
}); });
this.vnInterceptor.setToken(token); this.vnInterceptor.setToken(token, tokenMultimedia);
try { try {
if (remember) if (remember)
this.setStorage(localStorage, token, created, ttl); this.setStorage(localStorage, token, tokenMultimedia, created, ttl);
else else
this.setStorage(sessionStorage, token, created, ttl); this.setStorage(sessionStorage, token, tokenMultimedia, created, ttl);
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} }
@ -46,6 +47,7 @@ export default class Token {
unset() { unset() {
this.token = null; this.token = null;
this.tokenMultimedia = null;
this.created = null; this.created = null;
this.ttl = null; this.ttl = null;
this.remember = null; this.remember = null;
@ -57,13 +59,15 @@ export default class Token {
getStorage(storage) { getStorage(storage) {
this.token = storage.getItem('vnToken'); this.token = storage.getItem('vnToken');
this.tokenMultimedia = storage.getItem('vnTokenMultimedia');
if (!this.token) return; if (!this.token) return;
const created = storage.getItem('vnTokenCreated'); const created = storage.getItem('vnTokenCreated');
this.created = created && new Date(created); this.created = created && new Date(created);
this.ttl = storage.getItem('vnTokenTtl'); this.ttl = storage.getItem('vnTokenTtl');
} }
setStorage(storage, token, created, ttl) { setStorage(storage, token, tokenMultimedia, created, ttl) {
storage.setItem('vnTokenMultimedia', tokenMultimedia);
storage.setItem('vnToken', token); storage.setItem('vnToken', token);
storage.setItem('vnTokenCreated', created.toJSON()); storage.setItem('vnTokenCreated', created.toJSON());
storage.setItem('vnTokenTtl', ttl); storage.setItem('vnTokenTtl', ttl);
@ -71,6 +75,7 @@ export default class Token {
removeStorage(storage) { removeStorage(storage) {
storage.removeItem('vnToken'); storage.removeItem('vnToken');
storage.removeItem('vnTokenMultimedia');
storage.removeItem('vnTokenCreated'); storage.removeItem('vnTokenCreated');
storage.removeItem('vnTokenTtl'); storage.removeItem('vnTokenTtl');
} }

View File

@ -23,8 +23,7 @@ export class Layout extends Component {
if (!this.$.$root.user) return; if (!this.$.$root.user) return;
const userId = this.$.$root.user.id; const userId = this.$.$root.user.id;
const token = this.vnToken.token; return `/api/Images/user/160x160/${userId}/download?access_token=${this.vnToken.tokenMultimedia}`;
return `/api/Images/user/160x160/${userId}/download?access_token=${token}`;
} }
refresh() { refresh() {

View File

@ -31,7 +31,7 @@
ng-click="$ctrl.showDescriptor($event, userLog)"> ng-click="$ctrl.showDescriptor($event, userLog)">
<img <img
ng-if="::userLog.user.image" ng-if="::userLog.user.image"
ng-src="/api/Images/user/160x160/{{::userLog.userFk}}/download?access_token={{::$ctrl.vnToken.token}}"> ng-src="/api/Images/user/160x160/{{::userLog.userFk}}/download?access_token={{::$ctrl.vnToken.tokenMultimedia}}">
</img> </img>
</vn-avatar> </vn-avatar>
</div> </div>
@ -181,7 +181,7 @@
val="{{::nickname}}"> val="{{::nickname}}">
<img <img
ng-if="::image" ng-if="::image"
ng-src="/api/Images/user/160x160/{{::id}}/download?access_token={{::$ctrl.vnToken.token}}"> ng-src="/api/Images/user/160x160/{{::id}}/download?access_token={{::$ctrl.vnToken.tokenMultimedia}}">
</img> </img>
</vn-avatar> </vn-avatar>
<div> <div>

View File

@ -13,7 +13,7 @@ export function run($window, $rootScope, vnAuth, vnApp, vnToken, $state) {
if (!collection || !size || !id) return; if (!collection || !size || !id) return;
const basePath = `/api/Images/${collection}/${size}/${id}`; const basePath = `/api/Images/${collection}/${size}/${id}`;
return `${basePath}/download?access_token=${vnToken.token}`; return `${basePath}/download?access_token=${vnToken.tokenMultimedia}`;
}; };
$window.validations = {}; $window.validations = {};

View File

@ -220,5 +220,7 @@
"Shelving not valid": "Shelving not valid", "Shelving not valid": "Shelving not valid",
"printerNotExists": "The printer does not exist", "printerNotExists": "The printer does not exist",
"There are not picking tickets": "There are not picking tickets", "There are not picking tickets": "There are not picking tickets",
"ticketCommercial": "The ticket {{ ticket }} for the salesperson {{ salesMan }} is in preparation. (automatically generated message)" "ticketCommercial": "The ticket {{ ticket }} for the salesperson {{ salesMan }} is in preparation. (automatically generated message)",
"This password can only be changed by the user themselves": "This password can only be changed by the user themselves",
"They're not your subordinate": "They're not your subordinate"
} }

View File

@ -346,5 +346,7 @@
"CountryFK cannot be empty": "El país no puede estar vacío", "CountryFK cannot be empty": "El país no puede estar vacío",
"Cmr file does not exist": "El archivo del cmr no existe", "Cmr file does not exist": "El archivo del cmr no existe",
"You are not allowed to modify the alias": "No estás autorizado a modificar el alias", "You are not allowed to modify the alias": "No estás autorizado a modificar el alias",
"The address of the customer must have information about Incoterms and Customs Agent": "El consignatario del cliente debe tener informado Incoterms y Agente de aduanas" "The address of the customer must have information about Incoterms and Customs Agent": "El consignatario del cliente debe tener informado Incoterms y Agente de aduanas",
} "This password can only be changed by the user themselves": "Esta contraseña solo puede ser modificada por el propio usuario",
"They're not your subordinate": "No es tu subordinado/a."
}

View File

@ -15,7 +15,8 @@ module.exports = Self => {
http: { http: {
path: `/logout`, path: `/logout`,
verb: 'POST' verb: 'POST'
} },
accessScopes: ['DEFAULT', 'read:multimedia']
}); });
Self.logout = async ctx => Self.app.models.VnUser.logout(ctx.req.accessToken.id); Self.logout = async ctx => Self.app.models.VnUser.logout(ctx.req.accessToken.id);

View File

@ -1,4 +1,7 @@
const ForbiddenError = require('vn-loopback/util/forbiddenError');
const {models} = require('vn-loopback/server/server');
module.exports = Self => { module.exports = Self => {
require('../methods/account/sync')(Self); require('../methods/account/sync')(Self);
require('../methods/account/sync-by-id')(Self); require('../methods/account/sync-by-id')(Self);
@ -7,4 +10,11 @@ module.exports = Self => {
require('../methods/account/logout')(Self); require('../methods/account/logout')(Self);
require('../methods/account/change-password')(Self); require('../methods/account/change-password')(Self);
require('../methods/account/set-password')(Self); require('../methods/account/set-password')(Self);
Self.setUnverifiedPassword = async(id, pass, options) => {
const {emailVerified} = await models.VnUser.findById(id, {fields: ['emailVerified']}, options);
if (emailVerified) throw new ForbiddenError('This password can only be changed by the user themselves');
await models.VnUser.setPassword(id, pass, options);
};
}; };

View File

@ -32,7 +32,8 @@ module.exports = Self => {
http: { http: {
path: `/:id/downloadFile`, path: `/:id/downloadFile`,
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.downloadFile = async function(ctx, id) { Self.downloadFile = async function(ctx, id) {

View File

@ -114,7 +114,7 @@
<vn-td center shrink> <vn-td center shrink>
<a ng-show="balance.hasPdf" <a ng-show="balance.hasPdf"
target="_blank" target="_blank"
href="api/InvoiceOuts/{{::balance.id}}/download?access_token={{::$ctrl.vnToken.token}}"> href="api/InvoiceOuts/{{::balance.id}}/download?access_token={{::$ctrl.vnToken.tokenMultimedia}}">
<vn-icon-button <vn-icon-button
icon="cloud_download" icon="cloud_download"
title="{{'Download PDF' | translate}}"> title="{{'Download PDF' | translate}}">

View File

@ -31,7 +31,8 @@ module.exports = Self => {
http: { http: {
path: '/:id/download', path: '/:id/download',
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.download = async function(ctx, id, options) { Self.download = async function(ctx, id, options) {

View File

@ -31,7 +31,8 @@ module.exports = Self => {
http: { http: {
path: '/downloadZip', path: '/downloadZip',
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.downloadZip = async function(ctx, ids, options) { Self.downloadZip = async function(ctx, ids, options) {

View File

@ -37,7 +37,7 @@
<vn-menu vn-id="showInvoiceMenu"> <vn-menu vn-id="showInvoiceMenu">
<vn-list> <vn-list>
<a class="vn-item" <a class="vn-item"
href="api/InvoiceOuts/{{$ctrl.id}}/download?access_token={{$ctrl.vnToken.token}}" href="api/InvoiceOuts/{{$ctrl.id}}/download?access_token={{$ctrl.vnToken.tokenMultimedia}}"
target="_blank" target="_blank"
name="showInvoicePdf" name="showInvoicePdf"
translate> translate>
@ -102,7 +102,7 @@
</vn-item> </vn-item>
<vn-item class="dropdown" <vn-item class="dropdown"
vn-click-stop="refundMenu.show($event, 'left')" vn-click-stop="refundMenu.show($event, 'left')"
vn-tooltip="Create a single ticket with all the content of the current invoice" vn-tooltip="Create a refund ticket for each ticket on the current invoice"
vn-acl="invoicing, claimManager, salesAssistant" vn-acl="invoicing, claimManager, salesAssistant"
vn-acl-action="remove" vn-acl-action="remove"
translate> translate>

View File

@ -118,11 +118,14 @@ class Controller extends Section {
const query = 'InvoiceOuts/refund'; const query = 'InvoiceOuts/refund';
const params = {ref: this.invoiceOut.ref, withWarehouse: withWarehouse}; const params = {ref: this.invoiceOut.ref, withWarehouse: withWarehouse};
this.$http.post(query, params).then(res => { this.$http.post(query, params).then(res => {
const refundTicket = res.data; const tickets = res.data;
this.vnApp.showSuccess(this.$t('The following refund ticket have been created', { const refundTickets = tickets.map(ticket => ticket.id);
ticketId: refundTicket.id
this.vnApp.showSuccess(this.$t('The following refund tickets have been created', {
ticketId: refundTickets.join(',')
})); }));
this.$state.go('ticket.card.sale', {id: refundTicket.id}); if (refundTickets.length == 1)
this.$state.go('ticket.card.sale', {id: refundTickets[0]});
}); });
} }

View File

@ -15,7 +15,7 @@ Are you sure you want to clone this invoice?: Estas seguro de clonar esta factur
InvoiceOut booked: Factura asentada InvoiceOut booked: Factura asentada
Are you sure you want to book this invoice?: Estas seguro de querer asentar esta factura? Are you sure you want to book this invoice?: Estas seguro de querer asentar esta factura?
Are you sure you want to refund this invoice?: Estas seguro de querer abonar esta factura? Are you sure you want to refund this invoice?: Estas seguro de querer abonar esta factura?
Create a single ticket with all the content of the current invoice: Crear un ticket unico con todo el contenido de la factura actual Create a refund ticket for each ticket on the current invoice: Crear un ticket abono por cada ticket de la factura actual
Regenerate PDF invoice: Regenerar PDF factura Regenerate PDF invoice: Regenerar PDF factura
The invoice PDF document has been regenerated: El documento PDF de la factura ha sido regenerado The invoice PDF document has been regenerated: El documento PDF de la factura ha sido regenerado
The email can't be empty: El correo no puede estar vacío The email can't be empty: El correo no puede estar vacío

View File

@ -25,7 +25,7 @@ export default class Controller extends Section {
openPdf() { openPdf() {
if (this.checked.length <= 1) { if (this.checked.length <= 1) {
const [invoiceOutId] = this.checked; const [invoiceOutId] = this.checked;
const url = `api/InvoiceOuts/${invoiceOutId}/download?access_token=${this.vnToken.token}`; const url = `api/InvoiceOuts/${invoiceOutId}/download?access_token=${this.vnToken.tokenMultimedia}`;
window.open(url, '_blank'); window.open(url, '_blank');
} else { } else {
const invoiceOutIds = this.checked; const invoiceOutIds = this.checked;

View File

@ -11,6 +11,7 @@ module.exports = Self => {
path: `/download`, path: `/download`,
verb: 'POST', verb: 'POST',
}, },
accessScopes: ['read:multimedia']
}); });
Self.download = async() => { Self.download = async() => {

View File

@ -29,7 +29,8 @@ module.exports = Self => {
http: { http: {
path: '/downloadCmrsZip', path: '/downloadCmrsZip',
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.downloadCmrsZip = async function(ctx, ids, options) { Self.downloadCmrsZip = async function(ctx, ids, options) {

View File

@ -29,7 +29,8 @@ module.exports = Self => {
http: { http: {
path: '/downloadZip', path: '/downloadZip',
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.downloadZip = async function(ctx, id, options) { Self.downloadZip = async function(ctx, id, options) {

View File

@ -34,7 +34,9 @@ module.exports = Self => {
http: { http: {
path: '/:id/driver-route-pdf', path: '/:id/driver-route-pdf',
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.driverRoutePdf = (ctx, id) => Self.printReport(ctx, id, 'driver-route'); Self.driverRoutePdf = (ctx, id) => Self.printReport(ctx, id, 'driver-route');

View File

@ -30,9 +30,11 @@ module.exports = Self => {
}); });
function validateDistance(err) { function validateDistance(err) {
const routeTotalKm = this.kmEnd - this.kmStart; if (this.kmEnd) {
const routeMaxKm = 4000; const routeTotalKm = this.kmEnd - this.kmStart;
if (routeTotalKm > routeMaxKm || this.kmStart > this.kmEnd) const routeMaxKm = 4000;
err(); if (routeTotalKm > routeMaxKm || this.kmStart > this.kmEnd)
err();
}
} }
}; };

View File

@ -40,7 +40,7 @@ export default class Controller extends Section {
const stringRoutesIds = routesIds.join(','); const stringRoutesIds = routesIds.join(',');
if (this.checked.length <= 1) { if (this.checked.length <= 1) {
const url = `api/Routes/${stringRoutesIds}/driver-route-pdf?access_token=${this.vnToken.token}`; const url = `api/Routes/${stringRoutesIds}/driver-route-pdf?access_token=${this.vnToken.tokenMultimedia}`;
window.open(url, '_blank'); window.open(url, '_blank');
} else { } else {
const serializedParams = this.$httpParamSerializer({ const serializedParams = this.$httpParamSerializer({

View File

@ -9,8 +9,8 @@ describe('ticketLog getChanges()', () => {
it('should return the changes in the sales of a ticket', async() => { it('should return the changes in the sales of a ticket', async() => {
const ticketId = 16; const ticketId = 16;
const changues = await models.TicketLog.getChanges(ctx, ticketId); const changes = await models.TicketLog.getChanges(ctx, ticketId);
expect(changues).toContain(`Change quantity`); expect(changes).toContain(`Change quantity`);
}); });
}); });

View File

@ -58,6 +58,11 @@ module.exports = Self => {
AND t.refFk IS NULL AND t.refFk IS NULL
GROUP BY t.id GROUP BY t.id
`, [toDate, toDate]); `, [toDate, toDate]);
const ticketIds = tickets.map(ticket => ticket.id);
await Self.rawSql(`
INSERT INTO util.debug (variable, value)
VALUES ('nightInvoicing', ?)
`, [ticketIds.join(',')]);
await closure(ctx, Self, tickets); await closure(ctx, Self, tickets);

View File

@ -13,6 +13,8 @@ module.exports = async function(ctx, Self, tickets, reqArgs = {}) {
const failedtickets = []; const failedtickets = [];
for (const ticket of tickets) { for (const ticket of tickets) {
try { try {
await Self.rawSql(`CALL util.debugAdd('invoicingTicket', ?)`, [ticket.id], {userId});
await Self.app.models.InvoiceOut.getSerial(ticket.clientFk, ticket.companyFk, ticket.addressFk, 'M'); await Self.app.models.InvoiceOut.getSerial(ticket.clientFk, ticket.companyFk, ticket.addressFk, 'M');
await Self.rawSql( await Self.rawSql(
`CALL vn.ticket_closeByTicket(?)`, `CALL vn.ticket_closeByTicket(?)`,

View File

@ -29,6 +29,15 @@ module.exports = Self => {
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);
const ticketLog = await models.TicketLog.findOne({
fields: ['originFk', 'creationDate', 'newInstance'],
where: {
originFk: id,
newInstance: {like: '%"isDeleted":true%'}
},
order: 'creationDate DESC'
}, myOptions);
const ticket = await models.Ticket.findById(id, { const ticket = await models.Ticket.findById(id, {
include: [{ include: [{
relation: 'client', relation: 'client',
@ -39,10 +48,9 @@ module.exports = Self => {
}, myOptions); }, myOptions);
const now = Date.vnNew(); const now = Date.vnNew();
const maxDate = new Date(ticket.updated); const maxDate = new Date(ticketLog?.creationDate);
maxDate.setHours(maxDate.getHours() + 1); maxDate.setHours(maxDate.getHours() + 1);
if (!ticketLog || now > maxDate)
if (now > maxDate)
throw new UserError(`You can only restore a ticket within the first hour after deletion`); throw new UserError(`You can only restore a ticket within the first hour after deletion`);
// Send notification to salesPerson // Send notification to salesPerson

View File

@ -68,7 +68,7 @@ describe('ticket filter()', () => {
const filter = {}; const filter = {};
const result = await models.Ticket.filter(ctx, filter, options); const result = await models.Ticket.filter(ctx, filter, options);
expect(result.length).toEqual(6); expect(result.length).toEqual(7);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {

View File

@ -4,7 +4,7 @@ const models = app.models;
describe('ticket restore()', () => { describe('ticket restore()', () => {
const employeeUser = 1110; const employeeUser = 1110;
const ticketId = 18; const ticketId = 9;
const activeCtx = { const activeCtx = {
accessToken: {userId: employeeUser}, accessToken: {userId: employeeUser},
headers: { headers: {
@ -30,10 +30,21 @@ describe('ticket restore()', () => {
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
const ticket = await models.Ticket.findById(ticketId, null, options); const ticket = await models.Ticket.findById(ticketId, null, options);
await ticket.updateAttributes({ await ticket.updateAttributes({
isDeleted: true, isDeleted: true,
updated: now updated: now
}, options); }, options);
await models.TicketLog.create({
originFk: ticketId,
userFk: employeeUser,
action: 'update',
changedModel: 'Ticket',
creationDate: new Date('2001-01-01 10:59:00'),
newInstance: '{"isDeleted":true}'
}, options);
await app.models.Ticket.restore(ctx, ticketId, options); await app.models.Ticket.restore(ctx, ticketId, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -52,11 +63,21 @@ describe('ticket restore()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
const ticketBeforeUpdate = await models.Ticket.findById(ticketId, null, options); const ticketBeforeUpdate = await models.Ticket.findById(ticketId, null, options);
await ticketBeforeUpdate.updateAttributes({ await ticketBeforeUpdate.updateAttributes({
isDeleted: true, isDeleted: true,
updated: now updated: now
}, options); }, options);
await models.TicketLog.create({
originFk: ticketId,
userFk: employeeUser,
action: 'update',
changedModel: 'Ticket',
creationDate: new Date('2001-01-01 11:01:00'),
newInstance: '{"isDeleted":true}'
}, options);
const ticketAfterUpdate = await models.Ticket.findById(ticketId, null, options); const ticketAfterUpdate = await models.Ticket.findById(ticketId, null, options);
expect(ticketAfterUpdate.isDeleted).toBeTruthy(); expect(ticketAfterUpdate.isDeleted).toBeTruthy();
@ -65,7 +86,9 @@ describe('ticket restore()', () => {
const ticketAfterRestore = await models.Ticket.findById(ticketId, null, options); const ticketAfterRestore = await models.Ticket.findById(ticketId, null, options);
const fullYear = now.getFullYear(); const fullYear = now.getFullYear();
const shippedFullYear = ticketAfterRestore.shipped.getFullYear(); const shippedFullYear = ticketAfterRestore.shipped.getFullYear();
const landedFullYear = ticketAfterRestore.landed.getFullYear(); const landedFullYear = ticketAfterRestore.landed.getFullYear();
expect(ticketAfterRestore.isDeleted).toBeFalsy(); expect(ticketAfterRestore.isDeleted).toBeFalsy();

View File

@ -5,5 +5,40 @@
"mysql": { "mysql": {
"table": "ticketLog" "table": "ticketLog"
} }
} },
"properties": {
"id": {
"type": "string"
},
"originFk": {
"type": "number"
},
"userFk": {
"type":"number"
},
"action": {
"type": "string"
},
"creationDate": {
"type": "date"
},
"description": {
"type": "string"
},
"changedModel": {
"type": "string"
},
"oldInstance": {
"type": "any"
},
"newInstance": {
"type": "any"
},
"changedModelId": {
"type": "string"
},
"changedModelValue": {
"type": "string"
}
}
} }

View File

@ -1,4 +1,5 @@
const UserError = require('vn-loopback/util/user-error'); const UserError = require('vn-loopback/util/user-error');
const LoopBackContext = require('loopback-context');
module.exports = Self => { module.exports = Self => {
require('../methods/ticket-weekly/filter')(Self); require('../methods/ticket-weekly/filter')(Self);
@ -8,4 +9,11 @@ module.exports = Self => {
return new UserError(`This ticket is already on weekly tickets`); return new UserError(`This ticket is already on weekly tickets`);
return err; return err;
}); });
Self.observe('after save', async ctx => {
const loopBackContext = LoopBackContext.getCurrentContext();
const httpCtx = {req: loopBackContext.active};
const httpRequest = httpCtx.req.http;
await Self.app.models.Ticket.setDeleted(httpRequest, ctx.instance.ticketFk, ctx.options);
});
}; };

View File

@ -35,6 +35,29 @@ class Controller extends Section {
}); });
} }
}); });
const filter = {
fields: ['originFk', 'creationDate', 'newInstance'],
where: {
originFk: value,
newInstance: {like: '%"isDeleted":true%'}
},
order: 'creationDate DESC'
};
this.$http.get(`TicketLogs/findOne`, {filter})
.then(res => {
if (res && res.data) {
const now = Date.vnNew();
const maxDate = new Date(res.data.creationDate);
maxDate.setHours(maxDate.getHours() + 1);
if (now <= maxDate)
return this.canRestoreTicket = true;
}
this.canRestoreTicket = false;
})
.catch(() => {
this.canRestoreTicket = false;
});
} }
get isInvoiced() { get isInvoiced() {
@ -124,7 +147,8 @@ class Controller extends Section {
return this.$http.patch(`TicketWeeklies`, params) return this.$http.patch(`TicketWeeklies`, params)
.then(() => { .then(() => {
this.$.addTurn.hide(); this.$.addTurn.hide();
this.vnApp.showSuccess(this.$t('Data saved!')); this.vnApp.showSuccess(this.$t('Current ticket deleted and added to shift'));
this.reload();
}); });
} }
@ -171,15 +195,6 @@ class Controller extends Section {
}); });
} }
get canRestoreTicket() {
const isDeleted = this.ticket.isDeleted;
const now = Date.vnNew();
const maxDate = new Date(this.ticket.updated);
maxDate.setHours(maxDate.getHours() + 1);
return isDeleted && (now <= maxDate);
}
restoreTicket() { restoreTicket() {
return this.$http.post(`Tickets/${this.id}/restore`) return this.$http.post(`Tickets/${this.id}/restore`)
.then(() => this.reload()) .then(() => this.reload())

View File

@ -40,30 +40,8 @@ describe('Ticket Component vnTicketDescriptorMenu', () => {
controller.ticket = ticket; controller.ticket = ticket;
})); }));
describe('canRestoreTicket() getter', () => {
it('should return true for a ticket deleted within the last hour', () => {
controller.ticket.isDeleted = true;
controller.ticket.updated = Date.vnNew();
const result = controller.canRestoreTicket;
expect(result).toBeTruthy();
});
it('should return false for a ticket deleted more than one hour ago', () => {
const pastHour = Date.vnNew();
pastHour.setHours(pastHour.getHours() - 2);
controller.ticket.isDeleted = true;
controller.ticket.updated = pastHour;
const result = controller.canRestoreTicket;
expect(result).toBeFalsy();
});
});
describe('addTurn()', () => { describe('addTurn()', () => {
pending('refs #6302');
it('should make a query and call $.addTurn.hide() and vnApp.showSuccess()', () => { it('should make a query and call $.addTurn.hide() and vnApp.showSuccess()', () => {
controller.$.addTurn = {hide: () => {}}; controller.$.addTurn = {hide: () => {}};
jest.spyOn(controller.$.addTurn, 'hide'); jest.spyOn(controller.$.addTurn, 'hide');
@ -105,20 +83,6 @@ describe('Ticket Component vnTicketDescriptorMenu', () => {
}); });
}); });
describe('restoreTicket()', () => {
it('should make a query to restore the ticket and call vnApp.showSuccess()', () => {
jest.spyOn(controller, 'reload').mockReturnThis();
jest.spyOn(controller.vnApp, 'showSuccess');
$httpBackend.expectPOST(`Tickets/${ticket.id}/restore`).respond();
controller.restoreTicket();
$httpBackend.flush();
expect(controller.reload).toHaveBeenCalled();
expect(controller.vnApp.showSuccess).toHaveBeenCalled();
});
});
describe('showPdfDeliveryNote()', () => { describe('showPdfDeliveryNote()', () => {
it('should open a new window showing a delivery note PDF document', () => { it('should open a new window showing a delivery note PDF document', () => {
jest.spyOn(window, 'open').mockReturnThis(); jest.spyOn(window, 'open').mockReturnThis();

View File

@ -14,7 +14,8 @@ Refund all...: Abonar todo...
with warehouse: con almacén with warehouse: con almacén
without warehouse: sin almacén without warehouse: sin almacén
Invoice sent: Factura enviada Invoice sent: Factura enviada
The following refund ticket have been created: "Se ha creado siguiente ticket de abono: {{ticketId}}" The following refund ticket have been created: "Se ha creado el siguiente ticket de abono: {{ticketId}}"
The following refund tickets have been created: "Se han creado los siguientes tickets de abono: {{ticketId}}"
Transfer client: Transferir cliente Transfer client: Transferir cliente
Send SMS...: Enviar SMS... Send SMS...: Enviar SMS...
Notify changes: Notificar cambios Notify changes: Notificar cambios
@ -27,3 +28,4 @@ Create a single ticket with all the content of the current ticket: Crea un ticke
Set ticket weight: Establecer peso al ticket Set ticket weight: Establecer peso al ticket
Ticket weight: Peso del ticket Ticket weight: Peso del ticket
This address has incoterms, you should set the weight before invoice it: Este consigatario tiene incoterms, deberías establecer el peso antes de facturar This address has incoterms, you should set the weight before invoice it: Este consigatario tiene incoterms, deberías establecer el peso antes de facturar
Current ticket deleted and added to shift: Ticket actual borrado y añadido a turno

View File

@ -29,7 +29,8 @@ module.exports = Self => {
http: { http: {
path: `/:id/downloadFile`, path: `/:id/downloadFile`,
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.downloadFile = async function(ctx, id) { Self.downloadFile = async function(ctx, id) {

View File

@ -1,31 +1,29 @@
const UserError = require('vn-loopback/util/user-error'); const ForbiddenError = require('vn-loopback/util/forbiddenError');
module.exports = Self => { module.exports = Self => {
Self.remoteMethodCtx('setPassword', { Self.remoteMethodCtx('setPassword', {
description: 'Set a new password', description: 'Set a new password',
accepts: [ accepts: [{
{ arg: 'id',
arg: 'workerFk', type: 'number',
type: 'number', required: true,
required: true, description: 'The worker id',
description: 'The worker id', http: {source: 'path'}
}, }, {
{ arg: 'newPass',
arg: 'newPass', type: 'String',
type: 'String', required: true,
required: true, description: 'The new worker password'
description: 'The new worker password' }],
}
],
http: { http: {
path: `/:id/setPassword`, path: `/:id/setPassword`,
verb: 'PATCH' verb: 'PATCH'
} }
}); });
Self.setPassword = async(ctx, options) => { Self.setPassword = async(ctx, id, newPass, options) => {
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {};
const {args} = ctx;
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);
if (!myOptions.transaction) { if (!myOptions.transaction) {
@ -33,11 +31,10 @@ module.exports = Self => {
myOptions.transaction = tx; myOptions.transaction = tx;
} }
try { try {
const isSubordinate = await models.Worker.isSubordinate(ctx, args.workerFk, myOptions); const isSubordinate = await Self.isSubordinate(ctx, id, myOptions);
if (!isSubordinate) throw new UserError('You don\'t have enough privileges.'); if (!isSubordinate) throw new ForbiddenError('They\'re not your subordinate');
await models.VnUser.setPassword(args.workerFk, args.newPass, myOptions); await models.Account.setUnverifiedPassword(id, newPass, myOptions);
await models.VnUser.updateAll({id: args.workerFk}, {emailVerified: true}, myOptions);
if (tx) await tx.commit(); if (tx) await tx.commit();
} catch (e) { } catch (e) {

View File

@ -1,31 +1,30 @@
const UserError = require('vn-loopback/util/user-error'); const {models} = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('worker setPassword()', () => { describe('worker setPassword()', () => {
let ctx; let ctx;
const newPass = 'H3rn4d3z#';
const employeeId = 1;
const managerId = 20;
const administrativeId = 5;
beforeAll(() => { beforeAll(() => {
ctx = { ctx = {
req: { req: {
accessToken: {}, accessToken: {userId: managerId},
headers: {origin: 'http://localhost'} headers: {origin: 'http://localhost'}
}, },
args: {workerFk: 9}
}; };
}); });
beforeEach(() => { it('should change the password if it is a subordinate and the email is not verified', async() => {
ctx.req.accessToken.userId = 20;
ctx.args.newPass = 'H3rn4d3z#';
});
it('should change the password', async() => {
const tx = await models.Worker.beginTransaction({}); const tx = await models.Worker.beginTransaction({});
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
await models.Worker.setPassword(ctx, options); await models.Worker.setPassword(ctx, employeeId, newPass, options);
const isNewPass = await passHasBeenChanged(employeeId, newPass, options);
expect(isNewPass).toBeTrue();
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
await tx.rollback(); await tx.rollback();
@ -33,29 +32,48 @@ describe('worker setPassword()', () => {
} }
}); });
it('should throw an error: Password does not meet requirements', async() => { it('should not change the password if it is a subordinate and the email is verified', async() => {
const tx = await models.Collection.beginTransaction({}); const tx = await models.Worker.beginTransaction({});
ctx.args.newPass = 'Hi';
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
await models.Worker.setPassword(ctx, options); await models.VnUser.updateAll({id: employeeId}, {emailVerified: true}, options);
await models.Worker.setPassword(ctx, employeeId, newPass, options);
await tx.rollback();
} catch (e) {
expect(e.message).toEqual(`This password can only be changed by the user themselves`);
await tx.rollback();
}
});
it('should not change the password if it is not a subordinate', async() => {
const tx = await models.Worker.beginTransaction({});
try {
const options = {transaction: tx};
await models.Worker.setPassword(ctx, administrativeId, newPass, options);
await tx.rollback();
} catch (e) {
expect(e.message).toEqual(`They're not your subordinate`);
await tx.rollback();
}
});
it('should throw an error: Password does not meet requirements', async() => {
const tx = await models.Worker.beginTransaction({});
const newPass = 'Hi';
try {
const options = {transaction: tx};
await models.Worker.setPassword(ctx, employeeId, newPass, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
expect(e.sqlMessage).toEqual('Password does not meet requirements'); expect(e.sqlMessage).toEqual('Password does not meet requirements');
await tx.rollback(); await tx.rollback();
} }
}); });
it('should throw an error: You don\'t have enough privileges.', async() => {
ctx.req.accessToken.userId = 5;
const tx = await models.Collection.beginTransaction({});
try {
const options = {transaction: tx};
await models.Worker.setPassword(ctx, options);
await tx.rollback();
} catch (e) {
expect(e).toEqual(new UserError(`You don't have enough privileges.`));
await tx.rollback();
}
});
}); });
const passHasBeenChanged = async(userId, pass, options) => {
const user = await models.VnUser.findById(userId, null, options);
return user.hasPassword(pass);
};

View File

@ -62,6 +62,11 @@
"type": "belongsTo", "type": "belongsTo",
"model": "Worker", "model": "Worker",
"foreignKey": "workerFk" "foreignKey": "workerFk"
},
"workerActivity": {
"type": "belongsTo",
"model": "Worker",
"foreignKey": "workerActivityTypeFk"
} }
} }
} }

View File

@ -11,8 +11,8 @@
? 'Click to allow the user to be disabled' ? 'Click to allow the user to be disabled'
: 'Click to exclude the user from getting disabled'}} : 'Click to exclude the user from getting disabled'}}
</vn-item> </vn-item>
<vn-item ng-if="!$ctrl.worker.user.emailVerified" ng-click="setPassword.show()" translate> <vn-item ng-if="!$ctrl.worker.user.emailVerified && $ctrl.vnConfig.storage.currentUserWorkerId !=$ctrl.worker.id" ng-click="setPassword.show()" translate>
Change password Change password
</vn-item> </vn-item>
</slot-menu> </slot-menu>
<slot-body> <slot-body>

Some files were not shown because too many files have changed in this diff Show More