7167-testToMaster_2414 #2244

Merged
alexm merged 643 commits from 7167-testToMaster_2414 into master 2024-04-04 05:32:41 +00:00
208 changed files with 3278 additions and 1916 deletions

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

@ -4,20 +4,21 @@ describe('image download()', () => {
const collection = 'user'; const collection = 'user';
const size = '160x160'; const size = '160x160';
const employeeId = 1; const employeeId = 1;
const developerId = 9;
const jessicaJonesId = 1110;
const ctx = {req: {accessToken: {userId: employeeId}}}; const ctx = {req: {accessToken: {userId: employeeId}}};
it('should return the image content-type of the user', async() => { it('should return the image content-type of the user', async() => {
const userId = 9; const image = await models.Image.download(ctx, collection, size, developerId);
const image = await models.Image.download(ctx, collection, size, userId);
const contentType = image[1]; const contentType = image[1];
expect(contentType).toEqual('image/png'); expect(contentType).toEqual('image/png');
}); });
it(`should return false if the user doesn't have image`, async() => { it('should return the user profile picture', async() => {
const userId = 1110; const image = await models.Image.download(ctx, collection, size, jessicaJonesId);
const image = await models.Image.download(ctx, collection, size, userId); const fileName = image[2];
expect(image).toBeFalse(); expect(fileName).toMatch('1110.png');
}); });
}); });

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

@ -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

@ -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
@ -118,18 +118,18 @@ INSERT INTO `hedera`.`tpvConfig`(`id`, `currency`, `terminal`, `transactionType`
INSERT INTO `account`.`user`(`id`,`name`,`nickname`, `password`,`role`,`active`,`email`,`lang`, `image`) INSERT INTO `account`.`user`(`id`,`name`,`nickname`, `password`,`role`,`active`,`email`,`lang`, `image`)
VALUES VALUES
(1101, 'BruceWayne', 'Bruce Wayne', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'BruceWayne@mydomain.com', 'es', 'e7723f0b24ff05b32ed09d95196f2f29'), (1101, 'BruceWayne', 'Bruce Wayne', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'BruceWayne@mydomain.com', 'es','1101'),
(1102, 'PetterParker', 'Petter Parker', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'PetterParker@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), (1102, 'PetterParker', 'Petter Parker', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'PetterParker@mydomain.com', 'en','1102'),
(1103, 'ClarkKent', 'Clark Kent', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'ClarkKent@mydomain.com', 'fr', 'e7723f0b24ff05b32ed09d95196f2f29'), (1103, 'ClarkKent', 'Clark Kent', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'ClarkKent@mydomain.com', 'fr','1103'),
(1104, 'TonyStark', 'Tony Stark', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'TonyStark@mydomain.com', 'es', 'e7723f0b24ff05b32ed09d95196f2f29'), (1104, 'TonyStark', 'Tony Stark', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'TonyStark@mydomain.com', 'es','1104'),
(1105, 'MaxEisenhardt', 'Max Eisenhardt', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt', 'e7723f0b24ff05b32ed09d95196f2f29'), (1105, 'MaxEisenhardt', 'Max Eisenhardt', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt','1105'),
(1106, 'DavidCharlesHaller', 'David Charles Haller', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'DavidCharlesHaller@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), (1106, 'DavidCharlesHaller', 'David Charles Haller', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'DavidCharlesHaller@mydomain.com', 'en','1106'),
(1107, 'HankPym', 'Hank Pym', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'HankPym@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), (1107, 'HankPym', 'Hank Pym', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'HankPym@mydomain.com', 'en','1107'),
(1108, 'CharlesXavier', 'Charles Xavier', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'CharlesXavier@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), (1108, 'CharlesXavier', 'Charles Xavier', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'CharlesXavier@mydomain.com', 'en','1108'),
(1109, 'BruceBanner', 'Bruce Banner', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'BruceBanner@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), (1109, 'BruceBanner', 'Bruce Banner', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'BruceBanner@mydomain.com', 'en','1109'),
(1110, 'JessicaJones', 'Jessica Jones', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'JessicaJones@mydomain.com', 'en', NULL), (1110, 'JessicaJones', 'Jessica Jones', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'JessicaJones@mydomain.com', 'en','1110'),
(1111, 'Missing', 'Missing', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 0, NULL, 'en', NULL), (1111, 'Missing', 'Missing', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 0, NULL, 'en','e7723f0b24ff05b32ed09d95196f2f29'),
(1112, 'Trash', 'Trash', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 0, NULL, 'en', NULL); (1112, 'Trash', 'Trash', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 0, NULL, 'en','e7723f0b24ff05b32ed09d95196f2f29');
UPDATE account.`user` UPDATE account.`user`
SET passExpired = DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR) SET passExpired = DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR)
@ -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
@ -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
@ -1980,10 +1980,10 @@ INSERT INTO `pbx`.`sip`(`user_id`, `extension`)
(5, 1102), (5, 1102),
(9, 1201); (9, 1201);
INSERT INTO `vn`.`professionalCategory` (`id`, `name`, `level`, `dayBreak`) INSERT INTO `vn`.`professionalCategory` (`id`, `description`)
VALUES VALUES
(1, 'employee', NULL, NULL), (1, 'employee'),
(2, 'florist', NULL, NULL); (2, 'florist');
INSERT INTO `vn`.`calendarType` (`id`, `description`, `hoursWeek`, `isPartial`) INSERT INTO `vn`.`calendarType` (`id`, `description`, `hoursWeek`, `isPartial`)
VALUES VALUES
@ -2400,7 +2400,8 @@ INSERT INTO `vn`.`dmsType`(`id`, `name`, `readRoleFk`, `writeRoleFk`, `code`)
(18, 'dua', NULL, NULL, 'dua'), (18, 'dua', NULL, NULL, 'dua'),
(19, 'inmovilizado', NULL, NULL, 'fixedAssets'), (19, 'inmovilizado', NULL, NULL, 'fixedAssets'),
(20, 'Reclamación', 1, 1, 'claim'), (20, 'Reclamación', 1, 1, 'claim'),
(21, 'Entrada', 1, 1, 'entry'); (21, 'Entrada', 1, 1, 'entry'),
(22, 'Proveedor', 1, 1, 'supplier');
INSERT INTO `vn`.`dms`(`id`, `dmsTypeFk`, `file`, `contentType`, `workerFk`, `warehouseFk`, `companyFk`, `hardCopyNumber`, `hasFile`, `reference`, `description`, `created`) INSERT INTO `vn`.`dms`(`id`, `dmsTypeFk`, `file`, `contentType`, `workerFk`, `warehouseFk`, `companyFk`, `hardCopyNumber`, `hasFile`, `reference`, `description`, `created`)
VALUES VALUES
@ -2412,7 +2413,8 @@ INSERT INTO `vn`.`dms`(`id`, `dmsTypeFk`, `file`, `contentType`, `workerFk`, `wa
(6, 5, '6.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'NotExists', 'DoesNotExists', util.VN_CURDATE()), (6, 5, '6.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'NotExists', 'DoesNotExists', util.VN_CURDATE()),
(7, 20, '7.jpg', 'image/jpeg', 9, 1, 442, NULL, FALSE, '1', 'TICKET ID DEL CLIENTE BRUCE WAYNE ID 1101', util.VN_CURDATE()), (7, 20, '7.jpg', 'image/jpeg', 9, 1, 442, NULL, FALSE, '1', 'TICKET ID DEL CLIENTE BRUCE WAYNE ID 1101', util.VN_CURDATE()),
(8, 20, '8.mp4', 'video/mp4', 9, 1, 442, NULL, FALSE, '1', 'TICKET ID DEL CLIENTE BRUCE WAYNE ID 1101', util.VN_CURDATE()), (8, 20, '8.mp4', 'video/mp4', 9, 1, 442, NULL, FALSE, '1', 'TICKET ID DEL CLIENTE BRUCE WAYNE ID 1101', util.VN_CURDATE()),
(9, 21, '7.jpg', 'image/jpeg', 9, 1, 442, NULL, FALSE, '1', 'ENTRADA ID 1', util.VN_CURDATE()); (9, 21, '7.jpg', 'image/jpeg', 9, 1, 442, NULL, FALSE, '1', 'ENTRADA ID 1', util.VN_CURDATE()),
(10, 21, '7.jpg', 'image/jpeg', 9, 1, 442, NULL, FALSE, '1', 'ENTRADA DE PRUEBA', util.VN_CURDATE());
INSERT INTO `vn`.`claimDms`(`claimFk`, `dmsFk`) INSERT INTO `vn`.`claimDms`(`claimFk`, `dmsFk`)
VALUES VALUES
@ -2504,9 +2506,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 +2699,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,12 +2798,13 @@ 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;
TRUNCATE `util`.`notification`;
INSERT INTO `util`.`notification` (`id`, `name`, `description`) INSERT INTO `util`.`notification` (`id`, `name`, `description`)
VALUES VALUES
(1, 'print-email', 'notification fixture one'), (1, 'print-email', 'notification fixture one'),
@ -2809,8 +2812,10 @@ 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');
TRUNCATE `util`.`notificationAcl`;
INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`)
VALUES VALUES
(1, 9), (1, 9),
@ -2819,13 +2824,16 @@ INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`)
(3, 9), (3, 9),
(4, 1), (4, 1),
(5, 9), (5, 9),
(6, 9); (6, 9),
(7, 9);
TRUNCATE `util`.`notificationQueue`;
INSERT INTO `util`.`notificationQueue` (`id`, `notificationFk`, `params`, `authorFk`, `status`, `created`) INSERT INTO `util`.`notificationQueue` (`id`, `notificationFk`, `params`, `authorFk`, `status`, `created`)
VALUES VALUES
(1, 'print-email', '{"id": "1"}', 9, 'pending', util.VN_CURDATE()), (1, 'print-email', '{"id": "1"}', 9, 'pending', util.VN_CURDATE()),
(2, 'print-email', '{"id": "2"}', null, 'pending', util.VN_CURDATE()), (2, 'print-email', '{"id": "2"}', null, 'pending', util.VN_CURDATE()),
(3, 'print-email', null, null, 'pending', util.VN_CURDATE()); (3, 'print-email', null, null, 'pending', util.VN_CURDATE());
TRUNCATE `util`.`notificationSubscription`;
INSERT INTO `util`.`notificationSubscription` (`notificationFk`, `userFk`) INSERT INTO `util`.`notificationSubscription` (`notificationFk`, `userFk`)
VALUES VALUES
@ -2836,8 +2844,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 +2861,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 +2898,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 +3076,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 +3096,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 +3156,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 +3234,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 +3273,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 +3309,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 +3359,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 +3398,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 +3438,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 +3478,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 +3518,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 +3559,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 +3599,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 +3639,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 +3674,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 +3719,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 +3738,11 @@ 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');
INSERT INTO `vn`.`supplierDms`(`supplierFk`, `dmsFk`, `editorFk`)
VALUES
(1, 10, 9);

View File

@ -0,0 +1,22 @@
DELIMITER $$
CREATE OR REPLACE
DEFINER=`root`@`localhost`
EVENT `floranet`.`clean`
ON SCHEDULE EVERY 1 DAY
STARTS '2024-01-01 23:00:00.000'
ON COMPLETION PRESERVE
ENABLE
DO
BEGIN
DELETE
FROM `order`
WHERE created < CURDATE()
AND isPaid = FALSE;
DELETE c.*
FROM catalogue c
LEFT JOIN `order` o ON o.catalogueFk = c.id
WHERE c.created < CURDATE()
AND o.id IS NULL;
END$$
DELIMITER ;

View File

@ -0,0 +1,52 @@
DROP PROCEDURE IF EXISTS floranet.catalogue_get;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE floranet.catalogue_get(vLanded DATE, vPostalCode VARCHAR(15))
READS SQL DATA
BEGIN
/**
* Returns list, price and all the stuff regarding the floranet items
*
* @param vLanded Delivery date
* @param vPostalCode Delivery address postal code
*/
DECLARE vLastCatalogueFk INT;
START TRANSACTION;
SELECT * FROM catalogue FOR UPDATE;
SELECT MAX(id) INTO vLastCatalogueFk
FROM catalogue;
INSERT INTO catalogue(
name,
price,
itemFk,
dated,
postalCode,
`type`,
image,
description
)
SELECT i.name,
i.`size`,
i.id,
vLanded,
vPostalCode,
it.name,
CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image),
i.description
FROM vn.item i
JOIN vn.itemType it ON it.id = i.typeFk
WHERE it.code IN ('FNR','FNP');
SELECT *
FROM catalogue
WHERE id > IFNULL(vLastCatalogueFk,0);
COMMIT;
END$$
DELIMITER ;

View File

@ -0,0 +1,20 @@
DROP PROCEDURE IF EXISTS floranet.contact_request;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost`
PROCEDURE floranet.contact_request(
vName VARCHAR(100),
vPhone VARCHAR(15),
vEmail VARCHAR(100),
vMessage TEXT)
READS SQL DATA
BEGIN
/**
* Set actions for contact request.
*
* @param vPostalCode Delivery address postal code
*/
END$$
DELIMITER ;

View File

@ -0,0 +1,29 @@
DROP PROCEDURE IF EXISTS floranet.deliveryDate_get;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `floranet`.`deliveryDate_get`(vPostalCode VARCHAR(15))
READS SQL DATA
BEGIN
/**
* Returns available dates for this postalCode, in the next seven days
*
* @param vPostalCode Delivery address postal code
*/
DECLARE vCurrentDayOfWeek INT;
SET vCurrentDayOfWeek = DAYOFWEEK(NOW());
SELECT DISTINCT nextDay
FROM (
SELECT CURDATE() + INTERVAL IF(
apc.dayOfWeek >= vCurrentDayOfWeek,
apc.dayOfWeek - vCurrentDayOfWeek,
7 - apc.dayOfWeek
) DAY nextDay,
NOW() + INTERVAL apc.hoursInAdvance - 12 HOUR minDeliveryTime
FROM addressPostCode apc
WHERE apc.postCode = vPostalCode
HAVING nextDay > minDeliveryTime) sub;
END$$
DELIMITER ;

View File

@ -0,0 +1,25 @@
DROP PROCEDURE IF EXISTS floranet.order_confirm;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost`PROCEDURE floranet.order_confirm(vCatalogueFk INT)
READS SQL DATA
BEGIN
/** Update order.isPaid field
*
* @param vCatalogueFk floranet.catalogue.id
*
* @returns floranet.order.isPaid
*/
UPDATE `order`
SET isPaid = TRUE,
payed = NOW()
WHERE catalogueFk = vCatalogueFk;
SELECT isPaid
FROM `order`
WHERE catalogueFk = vCatalogueFk;
END$$
DELIMITER ;

View File

@ -0,0 +1,42 @@
DROP PROCEDURE IF EXISTS floranet.order_put;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE floranet.order_put(vOrder JSON)
READS SQL DATA
BEGIN
/**
* Get and process an order
*
* @param vOrder Data of the order
*
* Customer data: <customerName>, <email>, <customerPhone>
*
* Item data: <catalogueFk>, <message>
*
* Delivery data: <deliveryName>, <address>, <deliveryPhone>
*
*/
INSERT IGNORE INTO `order`(
catalogueFk,
customerName,
email,
customerPhone,
message,
deliveryName,
address,
deliveryPhone
)
VALUES (JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.catalogueFk')),
JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.customerName')),
JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.email')),
JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.customerPhone')),
JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.message')),
JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.deliveryName')),
JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.address')),
JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.deliveryPhone'))
);
SELECT LAST_INSERT_ID() orderFk;
END$$
DELIMITER ;

View File

@ -0,0 +1,19 @@
DROP PROCEDURE IF EXISTS floranet.sliders_get;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE floranet.sliders_get()
READS SQL DATA
BEGIN
/**
* Returns list of url for sliders
*/
SELECT
CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image) url,
i.longName
FROM vn.item i
JOIN vn.itemType it ON it.id = i.typeFk
WHERE it.code IN ('FNR','FNP');
END$$
DELIMITER ;

View File

@ -8,13 +8,16 @@ BEGIN
SELECT rate3 INTO price SELECT rate3 INTO price
FROM vn.priceFixed FROM vn.priceFixed
WHERE itemFk = vItemFk WHERE itemFk = vItemFk
AND util.VN_CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1; AND util.VN_CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1;
SELECT `value` INTO price SELECT `value` INTO price
FROM vn.specialPrice FROM vn.specialPrice
WHERE itemFk = vItemFk WHERE itemFk = vItemFk
AND clientFk = vClientFk ; AND (clientFk = vClientFk OR clientFk IS NULL)
AND started <= util.VN_CURDATE()
AND (ended >= util.VN_CURDATE() OR ended IS NULL)
ORDER BY id DESC LIMIT 1;
RETURN price; RETURN price;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -0,0 +1,102 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`absoluteInventoryHistory`(
vItemFk INT,
vWarehouseFk INT,
vDate DATETIME
)
BEGIN
/**
* Calcula y proporciona un historial de inventario absoluto
* para un artículo específico en un almacén dado
* hasta una fecha determinada.
*
* @param vItemFk Id de artículo
* @param vWarehouseFk Id de almacén
* @param vDate Fecha
*/
DECLARE vCalculatedInventory INT;
DECLARE vToday DATETIME DEFAULT util.VN_CURDATE();
DECLARE vStartDate DATE DEFAULT '2001-01-01';
CREATE OR REPLACE TEMPORARY TABLE tHistoricalPast
ENGINE = MEMORY
SELECT *
FROM (
SELECT tr.landed `date`,
b.quantity input,
NULL `output`,
tr.isReceived ok,
s.name alias,
e.invoiceNumber reference,
e.id id,
tr.isDelivered f5
FROM buy b
JOIN `entry` e ON e.id = b.entryFk
JOIN travel tr ON tr.id = e.travelFk
JOIN supplier s ON s.id = e.supplierFk
WHERE tr.landed >= vStartDate
AND s.id <> (SELECT supplierFk FROM inventoryConfig)
AND vWarehouseFk IN (tr.warehouseInFk, 0)
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
UNION ALL
SELECT tr.shipped,
NULL,
b.quantity,
tr.isDelivered,
s.name,
e.invoiceNumber,
e.id,
tr.isDelivered
FROM buy b
JOIN `entry` e ON e.id = b.entryFk
JOIN travel tr ON tr.id = e.travelFk
JOIN supplier s ON s.id = e.supplierFk
WHERE tr.shipped >= vStartDate
AND vWarehouseFk = tr.warehouseOutFk
AND s.id <> (SELECT supplierFk FROM inventoryConfig)
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
UNION ALL
SELECT t.shipped,
NULL,
m.quantity,
(m.isPicked OR t.isLabeled OR t.refFk IS NOT NULL),
t.nickname,
t.refFk,
t.id,
t.isPrinted
FROM sale m
JOIN ticket t ON t.id = m.ticketFk
JOIN client c ON c.id = t.clientFk
WHERE t.shipped >= vStartDate
AND m.itemFk = vItemFk
AND vWarehouseFk IN (t.warehouseFk, 0)
) t1
ORDER BY `date`, input DESC, ok DESC;
SELECT SUM(input) - SUM(`output`) INTO vCalculatedInventory
FROM tHistoricalPast
WHERE `date` < vDate;
SELECT p1.*, NULL v_virtual
FROM (
SELECT vDate `date`,
vCalculatedInventory input,
NULL `output`,
1 ok,
'Inventario calculado' alias,
'' reference,
0 id,
1 f5
UNION ALL
SELECT *
FROM tHistoricalPast
WHERE `date` >= vDate
) p1;
DROP TEMPORARY TABLE tHistoricalPast;
END$$
DELIMITER ;

View File

@ -0,0 +1,283 @@
DELIMITER $$
$$
CREATE OR REPLACE PROCEDURE vn.sale_boxPickingPrint(
IN vPrinterFk INT,
IN vSaleFk INT,
IN vPacking INT,
IN vSectorFk INT,
IN vUserFk INT,
IN vPackagingFk INT,
IN vPackingSiteFk INT)
BEGIN
/** Splits a line of sale to a different ticket and prints the transport sticker
*/
DECLARE vAgencyModeFk INT;
DECLARE vConcept VARCHAR(30);
DECLARE vExpeditionFk INT;
DECLARE vItemFk INT;
DECLARE vItemShelvingFk INT;
DECLARE vItemShelvingSaleFk INT;
DECLARE vItemShelvingSaleFk_old INT;
DECLARE vLastExpeditionTimeStamp DATETIME;
DECLARE vMaxPhoneLength INT DEFAULT 11;
DECLARE vMaxStreetLength INT DEFAULT 36;
DECLARE vNewSaleFk INT;
DECLARE vNewTicketFk INT;
DECLARE vParkingCode VARCHAR(10);
DECLARE vQuantity INT;
DECLARE vRemainder INT DEFAULT 0;
DECLARE vRemainderSaleFk INT;
DECLARE vShelving VARCHAR(10);
DECLARE vTicketFk INT;
SELECT s.quantity,
s.quantity MOD vPacking,
s.ticketFk,
s.itemFk,
s.concept
INTO vQuantity,
vRemainder,
vTicketFk,
vItemFk,
vConcept
FROM sale s
WHERE s.id = vSaleFk;
IF vRemainder THEN
UPDATE sale SET quantity = quantity - vRemainder WHERE id = vSaleFk;
INSERT INTO sale(ticketFk, itemFk, quantity, price, discount, concept)
SELECT ticketFk, itemFk, vRemainder, price, discount, concept
FROM sale
WHERE id = vSaleFk;
SET vRemainderSaleFk = LAST_INSERT_ID();
INSERT INTO saleComponent(saleFk, componentFk, value)
SELECT vRemainderSaleFk, componentFk, value
FROM saleComponent
WHERE saleFk = vSaleFk;
END IF;
w1: WHILE vQuantity >= vPacking DO
SET vItemShelvingFk = NULL;
SELECT sub.id
INTO vItemShelvingFk
FROM productionConfig pc
JOIN (
SELECT ish.id,
ish.visible - IFNULL(SUM(iss.quantity),0) available,
p.pickingOrder,
ish.created
FROM itemShelving ish
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN itemShelvingSale iss
ON iss.itemShelvingFk = ish.id
AND iss.created >= CURDATE()
AND iss.isPicked = FALSE
WHERE ish.itemFk = vItemFk
AND p.sectorFk = vSectorFk
GROUP BY ish.id
HAVING available >= vPacking) sub
ORDER BY IF(pc.orderMode = 'Location',sub.pickingOrder, sub.created)
LIMIT 1;
IF vItemShelvingFk THEN
INSERT INTO itemShelvingSale
SET itemShelvingFk = vItemShelvingFk,
saleFk = vSaleFk,
quantity = vPacking,
userFk = vUserFk,
isPicked = TRUE;
SET vItemShelvingSaleFk = LAST_INSERT_ID();
UPDATE sale SET isPicked = FALSE WHERE id = vSaleFk;
ELSE
LEAVE w1;
END IF;
SET vNewTicketFk = NULL;
SELECT MAX(t.id) INTO vNewTicketFk
FROM ticket t
JOIN ticketLastState tls ON tls.ticketFk = t.id
JOIN (SELECT addressFk, clientFk, date(shipped) shipped, warehouseFk
FROM ticket
WHERE id = vTicketFk) tt
ON tt.addressFk = t.addressFk
AND tt.clientFk = t.clientFk
AND t.shipped BETWEEN tt.shipped AND util.dayend(tt.shipped)
AND t.warehouseFk = tt.warehouseFk
WHERE tls.name = 'Encajado' ;
IF ISNULL(vNewTicketFk) THEN
INSERT INTO ticket( clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
warehouseFk,
companyFk,
landed,
zoneFk,
zonePrice,
zoneBonus,
routeFk,
priority,
hasPriority,
clonedFrom)
SELECT clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
warehouseFk,
companyFk,
landed,
zoneFk,
zonePrice,
zoneBonus,
routeFk,
priority,
hasPriority,
id
FROM ticket
WHERE id = vTicketFk;
SET vNewTicketFk = LAST_INSERT_ID();
INSERT INTO ticketTracking(ticketFk, stateFk, userFk)
SELECT vNewTicketFk, id, vUserFk
FROM state
WHERE code = 'PACKED';
END IF;
UPDATE sale SET quantity = quantity - vPacking WHERE id = vSaleFk;
UPDATE itemShelving SET visible = visible - vPacking WHERE id = vItemShelvingFk;
SET vNewSaleFk = NULL;
SELECT MAX(id) INTO vNewSaleFk
FROM sale
WHERE ticketFk = vNewTicketFk
AND itemFk = vItemFk;
IF vNewSaleFk THEN
UPDATE sale
SET quantity = quantity + vPacking
WHERE id = vNewSaleFk;
SET vItemShelvingSaleFk_old = NULL;
SELECT MAX(id) INTO vItemShelvingSaleFk_old
FROM itemShelvingSale
WHERE itemShelvingFk = vItemShelvingFk
AND saleFk = vNewSaleFk;
IF vItemShelvingSaleFk_old THEN
UPDATE itemShelvingSale
SET quantity = quantity + vPacking
WHERE id = vItemShelvingSaleFk_old;
DELETE FROM itemShelvingSale
WHERE id = vItemShelvingSaleFk;
SET vItemShelvingSaleFk = vItemShelvingSaleFk_old;
ELSE
UPDATE itemShelvingSale
SET saleFk = vNewSaleFk
WHERE id = vItemShelvingSaleFk;
END IF;
ELSE
INSERT INTO sale(ticketFk, itemFk, concept, quantity, discount, price)
SELECT vNewTicketFk, itemFk, concept, vPacking, discount, price
FROM sale
WHERE id = vSaleFk;
SET vNewSaleFk = LAST_INSERT_ID();
INSERT INTO saleComponent(saleFk, componentFk, value, isGreuge)
SELECT vNewSaleFk, componentFk, value, isGreuge
FROM saleComponent
WHERE saleFk = vSaleFk;
UPDATE itemShelvingSale
SET saleFk = vNewSaleFk
WHERE id = vItemShelvingSaleFk;
END IF;
INSERT IGNORE INTO saleTracking(saleFk, isChecked, workerFk, stateFk)
SELECT vNewSaleFk, TRUE, vUserFk, id
FROM state
WHERE code = 'PREPARED';
SELECT agencyModeFk INTO vAgencyModeFk
FROM ticket
WHERE id = vNewTicketFk;
INSERT INTO expedition(
agencyModeFk,
ticketFk,
freightItemFk,
workerFk,
packagingFk,
itemPackingTypeFk,
hostFk,
packingSiteFk,
monitorId,
started,
ended
)
SELECT vAgencyModeFk,
vNewTicketFk,
i.id,
vUserFk,
vPackagingFk,
ps.code,
h.code,
vPackingSiteFk,
ps.monitorId,
IFNULL(vLastExpeditionTimeStamp, NOW()),
NOW()
FROM packingSite ps
JOIN host h ON h.id = ps.hostFk
JOIN item i ON i.name = 'Shipping cost'
WHERE ps.id = vPackingSiteFk
LIMIT 1;
SET vExpeditionFk = LAST_INSERT_ID();
SET vLastExpeditionTimeStamp = NOW();
CALL dipole.expedition_Add(vExpeditionFk,vPrinterFk, TRUE);
SELECT shelvingFk, p.code
INTO vShelving, vParkingCode
FROM itemShelving ish
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
WHERE ish.id = vItemShelvingFk;
UPDATE dipole.expedition_PrintOut
SET isPrinted = FALSE,
itemFk = vItemFk,
quantity = vPacking,
longName = vConcept,
shelvingFk = vShelving,
parkingCode = vParkingCode,
phone = RIGHT(phone,vMaxPhoneLength),
street = RIGHT(street, vMAxStreetLength)
WHERE expeditionFk = vExpeditionFk;
DELETE FROM sale
WHERE quantity = 0
AND id = vSaleFk;
END WHILE;
END$$
DELIMITER ;

View File

@ -10,7 +10,7 @@ BEGIN
* Calcula los componentes de los articulos de tmp.ticketLot * Calcula los componentes de los articulos de tmp.ticketLot
* *
* @param vZoneFk para calcular el transporte * @param vZoneFk para calcular el transporte
* @param vAddressFk Consignatario * @param vAddressFk Consignatario
* @param vShipped dia de salida del pedido * @param vShipped dia de salida del pedido
* @param vWarehouseFk warehouse de salida del pedido * @param vWarehouseFk warehouse de salida del pedido
* @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) * @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk)
@ -24,7 +24,20 @@ BEGIN
SELECT clientFk INTO vClientFK SELECT clientFk INTO vClientFK
FROM address FROM address
WHERE id = vAddressFk; WHERE id = vAddressFk;
CREATE OR REPLACE TEMPORARY TABLE tSpecialPrice
(INDEX (itemFk))
ENGINE = MEMORY
SELECT * FROM (
SELECT *
FROM specialPrice
WHERE (clientFk = vClientFk OR clientFk IS NULL)
AND started <= vShipped
AND (ended >= vShipped OR ended IS NULL)
ORDER BY (clientFk = vClientFk) DESC, id DESC
LIMIT 10000000000000000000) t
GROUP BY itemFk;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate
(PRIMARY KEY (itemFk, warehouseFk)) (PRIMARY KEY (itemFk, warehouseFk))
ENGINE = MEMORY ENGINE = MEMORY
@ -36,7 +49,7 @@ BEGIN
IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing, IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing,
IFNULL(pf.`grouping`, b.`grouping`) `grouping`, IFNULL(pf.`grouping`, b.`grouping`) `grouping`,
ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, ABS(IFNULL(pf.box, b.groupingMode)) groupingMode,
tl.buyFk, tl.buyFk,
i.typeFk, i.typeFk,
IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping
FROM tmp.ticketLot tl FROM tmp.ticketLot tl
@ -44,8 +57,7 @@ BEGIN
JOIN item i ON i.id = tl.itemFk JOIN item i ON i.id = tl.itemFk
JOIN itemType it ON it.id = i.typeFk JOIN itemType it ON it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN specialPrice sp ON sp.itemFk = i.id LEFT JOIN tSpecialPrice sp ON sp.itemFk = i.id
AND sp.clientFk = vClientFk
LEFT JOIN ( LEFT JOIN (
SELECT * FROM ( SELECT * FROM (
SELECT pf.itemFk, SELECT pf.itemFk,
@ -63,7 +75,7 @@ BEGIN
LIMIT 10000000000000000000 LIMIT 10000000000000000000
) tpf ) tpf
GROUP BY tpf.itemFk, tpf.warehouseFk GROUP BY tpf.itemFk, tpf.warehouseFk
) pf ON pf.itemFk = tl.itemFk ) pf ON pf.itemFk = tl.itemFk
AND pf.warehouseFk = tl.warehouseFk AND pf.warehouseFk = tl.warehouseFk
WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01
AND ic.merchandise AND ic.merchandise
@ -95,10 +107,10 @@ BEGIN
FROM tmp.ticketComponent tc FROM tmp.ticketComponent tc
JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk
GROUP BY tc.itemFk, warehouseFk; GROUP BY tc.itemFk, warehouseFk;
-- RECOBRO -- RECOBRO
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk, tcb.itemFk, c2.id, SELECT tcb.warehouseFk, tcb.itemFk, c2.id,
ROUND(tcb.base * ROUND(tcb.base *
LEAST( LEAST(
MAX(GREATEST(IFNULL(cr.priceIncreasing,0), MAX(GREATEST(IFNULL(cr.priceIncreasing,0),
@ -129,29 +141,29 @@ BEGIN
ROUND(base * wm.pricesModifierRate, 3) manaAuto ROUND(base * wm.pricesModifierRate, 3) manaAuto
FROM tmp.ticketComponentBase tcb FROM tmp.ticketComponentBase tcb
JOIN `client` c on c.id = vClientFk JOIN `client` c on c.id = vClientFk
JOIN workerMana wm ON c.salesPersonFk = wm.workerFk JOIN workerMana wm ON c.salesPersonFk = wm.workerFk
JOIN vn.component c2 ON c2.code = 'autoMana' JOIN vn.component c2 ON c2.code = 'autoMana'
WHERE wm.isPricesModifierActivated WHERE wm.isPricesModifierActivated
HAVING manaAuto <> 0; HAVING manaAuto <> 0;
-- Precios especiales -- Precios especiales
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk, SELECT tcb.warehouseFk,
tcb.itemFk, tcb.itemFk,
c2.id, c2.id,
GREATEST( GREATEST(
IFNULL(ROUND(tcb.base * c2.tax, 4), 0), IFNULL(ROUND(tcb.base * c2.tax, 4), 0),
IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3 IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3
) cost ) cost
FROM tmp.ticketComponentBase tcb FROM tmp.ticketComponentBase tcb
JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount' JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount'
JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk
LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk LEFT JOIN tSpecialPrice sp ON sp.itemFk = tcc.itemFk
JOIN vn.item i ON i.id = tcb.itemFk JOIN vn.item i ON i.id = tcb.itemFk
WHERE sp.value IS NULL WHERE sp.value IS NULL
AND i.supplyResponseFk IS NULL; AND i.supplyResponseFk IS NULL;
-- Individual -- Individual
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk, SELECT tcb.warehouseFk,
tcb.itemFk, tcb.itemFk,
@ -162,14 +174,14 @@ BEGIN
JOIN vn.client c ON c.id = vClientFk JOIN vn.client c ON c.id = vClientFk
JOIN vn.businessType bt ON bt.code = c.businessTypeFk JOIN vn.businessType bt ON bt.code = c.businessTypeFk
WHERE bt.code = 'individual'; WHERE bt.code = 'individual';
-- Venta por paquetes -- Venta por paquetes
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3
FROM tmp.ticketComponentCalculate tcc FROM tmp.ticketComponentCalculate tcc
JOIN vn.component c2 ON c2.code = 'salePerPackage' JOIN vn.component c2 ON c2.code = 'salePerPackage'
JOIN buy b ON b.id = tcc.buyFk JOIN buy b ON b.id = tcc.buyFk
LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk LEFT JOIN tSpecialPrice sp ON sp.itemFk = tcc.itemFk
WHERE sp.value IS NULL; WHERE sp.value IS NULL;
CREATE OR REPLACE TEMPORARY TABLE tmp.`zone` (INDEX (id)) CREATE OR REPLACE TEMPORARY TABLE tmp.`zone` (INDEX (id))
@ -177,7 +189,7 @@ BEGIN
SELECT vZoneFk id; SELECT vZoneFk id;
CALL zone_getOptionsForShipment(vShipped, TRUE); CALL zone_getOptionsForShipment(vShipped, TRUE);
-- Reparto -- Reparto
INSERT INTO tmp.ticketComponent INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFK, SELECT tcc.warehouseFK,
@ -191,7 +203,7 @@ BEGIN
JOIN agencyMode am ON am.id = z.agencyModeFk JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN vn.volumeConfig vc JOIN vn.volumeConfig vc
JOIN vn.component c2 ON c2.code = 'delivery' JOIN vn.component c2 ON c2.code = 'delivery'
LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk
AND ic.itemFk = tcc.itemFk AND ic.itemFk = tcc.itemFk
HAVING cost <> 0; HAVING cost <> 0;
@ -208,7 +220,7 @@ BEGIN
sp.value - SUM(tcc.cost) sumCost sp.value - SUM(tcc.cost) sumCost
FROM tmp.ticketComponentCopy tcc FROM tmp.ticketComponentCopy tcc
JOIN component c ON c.id = tcc.componentFk JOIN component c ON c.id = tcc.componentFk
JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk JOIN tSpecialPrice sp ON sp.itemFk = tcc.itemFk
JOIN vn.component c2 ON c2.code = 'specialPrices' JOIN vn.component c2 ON c2.code = 'specialPrices'
WHERE c.classRate IS NULL WHERE c.classRate IS NULL
AND tcc.warehouseFk = vWarehouseFk AND tcc.warehouseFk = vWarehouseFk
@ -244,9 +256,9 @@ BEGIN
CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price,
CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg
FROM tmp.ticketComponentCalculate tcc FROM tmp.ticketComponentCalculate tcc
JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
AND tcs.warehouseFk = tcc.warehouseFk AND tcs.warehouseFk = tcc.warehouseFk
WHERE IFNULL(tcs.classRate, 1) = 1 WHERE IFNULL(tcs.classRate, 1) = 1
AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0)
GROUP BY tcs.warehouseFk, tcs.itemFk; GROUP BY tcs.warehouseFk, tcs.itemFk;
@ -283,12 +295,13 @@ BEGIN
SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000 SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000
) t ) t
GROUP BY itemFk, warehouseFk, `grouping`; GROUP BY itemFk, warehouseFk, `grouping`;
DROP TEMPORARY TABLE DROP TEMPORARY TABLE
tmp.ticketComponentCalculate, tmp.ticketComponentCalculate,
tmp.ticketComponentSum, tmp.ticketComponentSum,
tmp.ticketComponentBase, tmp.ticketComponentBase,
tmp.ticketComponentRate, tmp.ticketComponentRate,
tmp.ticketComponentCopy; tmp.ticketComponentCopy,
tSpecialPrice;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -12,7 +12,7 @@ BEGIN
DECLARE v1Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 1 YEAR; DECLARE v1Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 1 YEAR;
DECLARE v2Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 YEAR; DECLARE v2Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 YEAR;
DECLARE v4Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 4 YEAR; DECLARE v4Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 4 YEAR;
DECLARE v5Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 5 YEAR; DECLARE v5Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 5 YEAR;
DECLARE vTrashId VARCHAR(15); DECLARE vTrashId VARCHAR(15);
DECLARE vCompanyBlk INT; DECLARE vCompanyBlk INT;
@ -30,8 +30,9 @@ BEGIN
DELETE IGNORE FROM expedition WHERE created < v26Months; DELETE IGNORE FROM expedition WHERE created < v26Months;
DELETE FROM sms WHERE created < v18Months; DELETE FROM sms WHERE created < v18Months;
DELETE FROM saleTracking WHERE created < v1Years; DELETE FROM saleTracking WHERE created < v1Years;
DELETE FROM productionError WHERE dated < v1Years;
DELETE FROM ticketTracking WHERE created < v18Months; DELETE FROM ticketTracking WHERE created < v18Months;
DELETE tobs FROM ticketObservation tobs DELETE tobs FROM ticketObservation tobs
JOIN ticket t ON tobs.ticketFk = t.id JOIN ticket t ON tobs.ticketFk = t.id
WHERE t.shipped < v5Years; WHERE t.shipped < v5Years;
DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < v1Years; DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < v1Years;
@ -113,12 +114,12 @@ BEGIN
FROM travel t FROM travel t
LEFT JOIN entry e ON e.travelFk = t.id LEFT JOIN entry e ON e.travelFk = t.id
WHERE t.shipped < v3Months AND e.travelFk IS NULL; WHERE t.shipped < v3Months AND e.travelFk IS NULL;
UPDATE dms d UPDATE dms d
JOIN dmsType dt ON dt.id = d.dmsTypeFk JOIN dmsType dt ON dt.id = d.dmsTypeFk
SET d.dmsTypeFk = vTrashId SET d.dmsTypeFk = vTrashId
WHERE created < util.VN_CURDATE() - INTERVAL dt.monthToDelete MONTH; WHERE created < util.VN_CURDATE() - INTERVAL dt.monthToDelete MONTH;
-- borrar entradas sin compras -- borrar entradas sin compras
CREATE OR REPLACE TEMPORARY TABLE tEntryToDelete CREATE OR REPLACE TEMPORARY TABLE tEntryToDelete
SELECT e.* SELECT e.*
@ -136,7 +137,7 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tRouteToDelete CREATE OR REPLACE TEMPORARY TABLE tRouteToDelete
SELECT * SELECT *
FROM route r FROM route r
WHERE created < v4Years; WHERE created < v4Years;
UPDATE tRouteToDelete tmp UPDATE tRouteToDelete tmp
JOIN dms d ON d.id = tmp.gestdocFk JOIN dms d ON d.id = tmp.gestdocFk
@ -180,7 +181,7 @@ BEGIN
DELETE FROM mail WHERE creationDate < v2Months; DELETE FROM mail WHERE creationDate < v2Months;
DELETE FROM split WHERE dated < v18Months; DELETE FROM split WHERE dated < v18Months;
DELETE FROM remittance WHERE dated < v18Months; DELETE FROM remittance WHERE dated < v18Months;
CREATE OR REPLACE TEMPORARY TABLE tTicketDelete CREATE OR REPLACE TEMPORARY TABLE tTicketDelete
SELECT DISTINCT tl.originFk ticketFk SELECT DISTINCT tl.originFk ticketFk
FROM ticketLog tl FROM ticketLog tl
@ -189,11 +190,11 @@ BEGIN
FROM ticket t FROM ticket t
JOIN ticketLog tl ON tl.originFk = t.id JOIN ticketLog tl ON tl.originFk = t.id
LEFT JOIN ticketWeekly tw ON tw.ticketFk = t.id LEFT JOIN ticketWeekly tw ON tw.ticketFk = t.id
WHERE t.shipped BETWEEN '2000-01-01' AND '2000-12-31' WHERE t.shipped BETWEEN '2000-01-01' AND '2000-12-31'
AND t.isDeleted AND t.isDeleted
AND tw.ticketFk IS NULL AND tw.ticketFk IS NULL
GROUP BY t.id GROUP BY t.id
) sub ON sub.ids = tl.id ) sub ON sub.ids = tl.id
WHERE tl.creationDate <= v2Months; WHERE tl.creationDate <= v2Months;
DELETE t DELETE t
FROM ticket t FROM ticket t

View File

@ -7,194 +7,195 @@ BEGIN
* @param vSelf company id * @param vSelf company id
* @param vMonthAgo time interval to be consulted * @param vMonthAgo time interval to be consulted
*/ */
DECLARE vStartingDate DATETIME DEFAULT TIMESTAMPADD (MONTH,- vMonthsAgo,util.VN_CURDATE()); DECLARE vStartingDate DATETIME DEFAULT TIMESTAMPADD (MONTH,- vMonthsAgo,util.VN_CURDATE());
DECLARE vCurrencyEuroFk INT; DECLARE vCurrencyEuroFk INT;
DECLARE vStartDate DATE; DECLARE vStartDate DATE;
DECLARE vInvalidBalances DOUBLE; DECLARE vInvalidBalances DOUBLE;
SELECT dated, invalidBalances INTO vStartDate, vInvalidBalances FROM supplierDebtConfig; SELECT dated, invalidBalances INTO vStartDate, vInvalidBalances FROM supplierDebtConfig;
SELECT id INTO vCurrencyEuroFk FROM currency WHERE code = 'EUR'; SELECT id INTO vCurrencyEuroFk FROM currency WHERE code = 'EUR';
DROP TEMPORARY TABLE IF EXISTS tOpeningBalances; DROP TEMPORARY TABLE IF EXISTS tOpeningBalances;
CREATE TEMPORARY TABLE tOpeningBalances ( CREATE TEMPORARY TABLE tOpeningBalances (
supplierFk INT NOT NULL, supplierFk INT NOT NULL,
companyFk INT NOT NULL, companyFk INT NOT NULL,
openingBalances DOUBLE NOT NULL, openingBalances DOUBLE NOT NULL,
closingBalances DOUBLE NOT NULL, closingBalances DOUBLE NOT NULL,
currencyFk INT NOT NULL, currencyFk INT NOT NULL,
PRIMARY KEY (supplierFk, companyFk, currencyFk) PRIMARY KEY (supplierFk, companyFk, currencyFk)
) ENGINE = MEMORY; ) ENGINE = MEMORY;
-- Calculates the opening and closing balance for each supplier -- Calculates the opening and closing balance for each supplier
INSERT INTO tOpeningBalances INSERT INTO tOpeningBalances
SELECT supplierFk, SELECT supplierFk,
companyFk, companyFk,
SUM(amount * isBeforeStarting) AS openingBalances, SUM(amount * isBeforeStarting) AS openingBalances,
SUM(amount) closingBalances, SUM(amount) closingBalances,
currencyFk currencyFk
FROM ( FROM (
SELECT p.supplierFk, SELECT p.supplierFk,
p.companyFk, p.companyFk,
IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa) AS amount, IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa) AS amount,
p.dueDated < vStartingDate isBeforeStarting, p.dueDated < vStartingDate isBeforeStarting,
p.currencyFk p.currencyFk
FROM payment p FROM payment p
WHERE p.received > vStartDate WHERE p.received > vStartDate
AND p.companyFk = vSelf AND p.companyFk = vSelf
UNION ALL UNION ALL
SELECT r.supplierFk, SELECT r.supplierFk,
r.companyFk, r.companyFk,
- IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue) AS Total, - IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue) AS Total,
rv.dueDated < vStartingDate isBeforeStarting, rv.dueDated < vStartingDate isBeforeStarting,
r.currencyFk r.currencyFk
FROM invoiceIn r FROM invoiceIn r
INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk
WHERE r.issued > vStartDate WHERE r.issued > vStartDate
AND r.isBooked AND r.isBooked
AND r.companyFk = vSelf AND r.companyFk = vSelf
) sub GROUP BY companyFk, supplierFk, currencyFk; ) sub GROUP BY companyFk, supplierFk, currencyFk;
DROP TEMPORARY TABLE IF EXISTS tPendingDuedates; DROP TEMPORARY TABLE IF EXISTS tPendingDuedates;
CREATE TEMPORARY TABLE tPendingDuedates ( CREATE TEMPORARY TABLE tPendingDuedates (
id INT auto_increment, id INT auto_increment,
expirationId INT, expirationId INT,
dated DATE, dated DATE,
supplierFk INT NOT NULL, supplierFk INT NOT NULL,
companyFk INT NOT NULL, companyFk INT NOT NULL,
amount DECIMAL(10, 2) NOT NULL, amount DECIMAL(10, 2) NOT NULL,
currencyFk INT NOT NULL, currencyFk INT NOT NULL,
pending DECIMAL(10, 2) DEFAULT 0, pending DECIMAL(10, 2) DEFAULT 0,
balance DECIMAL(10, 2) DEFAULT 0, balance DECIMAL(10, 2) DEFAULT 0,
endingBalance DECIMAL(10, 2) DEFAULT 0, endingBalance DECIMAL(10, 2) DEFAULT 0,
isPayment BOOLEAN, isPayment BOOLEAN,
isReconciled BOOLEAN, isReconciled BOOLEAN,
PRIMARY KEY (id), PRIMARY KEY (id),
INDEX (supplierFk, companyFk, currencyFk) INDEX (supplierFk, companyFk, currencyFk)
) ENGINE = MEMORY; ) ENGINE = MEMORY;
INSERT INTO tPendingDuedates ( INSERT INTO tPendingDuedates (
expirationId, expirationId,
dated, dated,
supplierFk, supplierFk,
companyFk, companyFk,
amount, amount,
currencyFk, currencyFk,
isPayment, isPayment,
isReconciled isReconciled
)SELECT p.id, )SELECT p.id,
p.dueDated, p.dueDated,
p.supplierFk, p.supplierFk,
p.companyFk, p.companyFk,
IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa), IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa),
p.currencyFk, p.currencyFk,
TRUE isPayment, TRUE isPayment,
p.isConciliated p.isConciliated
FROM payment p FROM payment p
WHERE p.dueDated >= vStartingDate WHERE p.dueDated >= vStartingDate
AND p.companyFk = vSelf AND p.companyFk = vSelf
UNION ALL UNION ALL
SELECT r.id, SELECT r.id,
rv.dueDated, rv.dueDated,
r.supplierFk, r.supplierFk,
r.companyFk, r.companyFk,
-IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue), -IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue),
r.currencyFk, r.currencyFk,
FALSE isPayment, FALSE isPayment,
TRUE TRUE
FROM invoiceIn r FROM invoiceIn r
LEFT JOIN tOpeningBalances si ON r.companyFk = si.companyFk LEFT JOIN tOpeningBalances si ON r.companyFk = si.companyFk
AND r.supplierFk = si.supplierFk AND r.supplierFk = si.supplierFk
AND r.currencyFk = si.currencyFk AND r.currencyFk = si.currencyFk
JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk
WHERE rv.dueDated >= vStartingDate WHERE rv.dueDated >= vStartingDate
AND (si.closingBalances IS NULL OR si.closingBalances <> 0) AND (si.closingBalances IS NULL OR si.closingBalances <> 0)
AND r.isBooked AND r.isBooked
AND r.companyFk = vSelf AND r.companyFk = vSelf
ORDER BY supplierFk, companyFk, companyFk, dueDated, isPayment DESC, id; ORDER BY supplierFk, companyFk, companyFk, dueDated, isPayment DESC, id;
-- Now, we calculate the outstanding amount for each receipt in descending order -- Now, we calculate the outstanding amount for each receipt in descending order
SET @risk := 0.0; SET @risk := 0.0;
SET @supplier := 0.0; SET @supplier := 0.0;
SET @company := 0.0; SET @company := 0.0;
SET @moneda := 0.0; SET @moneda := 0.0;
SET @pending := 0.0; SET @pending := 0.0;
SET @day := util.VN_CURDATE(); SET @day := util.VN_CURDATE();
UPDATE tPendingDuedates vp UPDATE tPendingDuedates vp
LEFT JOIN tOpeningBalances si ON vp.companyFk = si.companyFk LEFT JOIN tOpeningBalances si ON vp.companyFk = si.companyFk
AND vp.supplierFk = si.supplierFk AND vp.supplierFk = si.supplierFk
AND vp.currencyFk = si.currencyFk AND vp.currencyFk = si.currencyFk
SET vp.balance = @risk := ( SET vp.balance = @risk := (
IF ( IF (
@company <> vp.companyFk @company <> vp.companyFk
OR @supplier <> vp.supplierFk OR @supplier <> vp.supplierFk
OR @moneda <> vp.currencyFk, OR @moneda <> vp.currencyFk,
IFNULL(si.openingBalances, 0), IFNULL(si.openingBalances, 0),
@risk @risk
) + ) +
vp.amount vp.amount
), ),
-- if there is a change of company or supplier or currency, the balance is reset -- if there is a change of company or supplier or currency, the balance is reset
vp.pending = @pending := IF ( vp.pending = @pending := IF (
@company <> vp.companyFk @company <> vp.companyFk
OR @supplier <> vp.supplierFk OR @supplier <> vp.supplierFk
OR @moneda <> vp.currencyFk OR @moneda <> vp.currencyFk
OR @day <> vp.dated, OR @day <> vp.dated,
vp.amount * (NOT vp.isPayment), vp.amount * (NOT vp.isPayment),
@pending + vp.amount @pending + vp.amount
), ),
vp.companyFk = @company := vp.companyFk, vp.companyFk = @company := vp.companyFk,
vp.supplierFk = @supplier := vp.supplierFk, vp.supplierFk = @supplier := vp.supplierFk,
vp.currencyFk = @moneda := vp.currencyFk, vp.currencyFk = @moneda := vp.currencyFk,
vp.dated = @day := vp.dated, vp.dated = @day := vp.dated,
vp.balance = @risk, vp.balance = @risk,
vp.pending = @pending; vp.pending = @pending;
CREATE OR REPLACE TEMPORARY TABLE tRowsToDelete ENGINE = MEMORY CREATE OR REPLACE TEMPORARY TABLE tRowsToDelete ENGINE = MEMORY
SELECT expirationId, SELECT expirationId,
dated, dated,
supplierFk, supplierFk,
companyFk, companyFk,
currencyFk, currencyFk,
balance balance
FROM tPendingDuedates FROM tPendingDuedates
WHERE balance < vInvalidBalances WHERE balance < vInvalidBalances
AND balance > - vInvalidBalances; AND balance > - vInvalidBalances;
DELETE vp.*
FROM tPendingDuedates vp
JOIN tRowsToDelete rd ON (
vp.dated < rd.dated
OR (vp.dated = rd.dated AND vp.expirationId <= rd.expirationId)
)
AND vp.supplierFk = rd.supplierFk
AND vp.companyFk = rd.companyFk
AND vp.currencyFk = rd.currencyFk
WHERE NOT vp.isPayment;
SELECT vp.expirationId, DELETE vp.*
vp.dated, FROM tPendingDuedates vp
vp.supplierFk, JOIN tRowsToDelete rd ON (
vp.companyFk, vp.dated < rd.dated
vp.currencyFk, OR (vp.dated = rd.dated AND vp.expirationId <= rd.expirationId)
vp.amount, )
vp.pending, AND vp.supplierFk = rd.supplierFk
vp.balance, AND vp.companyFk = rd.companyFk
s.payMethodFk, AND vp.currencyFk = rd.currencyFk
vp.isPayment, WHERE NOT vp.isPayment;
vp.isReconciled,
vp.endingBalance, SELECT vp.expirationId,
cr.amount clientRiskAmount, vp.dated,
co.CEE vp.supplierFk,
FROM tPendingDuedates vp vp.companyFk,
LEFT JOIN supplier s ON s.id = vp.supplierFk vp.currencyFk,
LEFT JOIN client c ON c.fi = s.nif vp.amount,
JOIN clientRisk cr ON cr.clientFk = c.id AND cr.companyFk = vp.companyFk vp.pending,
LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id vp.balance,
LEFT JOIN bankEntity be ON be.id = sa.bankEntityFk s.payMethodFk,
LEFT JOIN country co ON co.id = be.countryFk; vp.isPayment,
vp.isReconciled,
DROP TEMPORARY TABLE tOpeningBalances; vp.endingBalance,
DROP TEMPORARY TABLE tPendingDuedates; cr.amount clientRiskAmount,
DROP TEMPORARY TABLE tRowsToDelete; co.CEE
FROM tPendingDuedates vp
LEFT JOIN supplier s ON s.id = vp.supplierFk
LEFT JOIN client c ON c.fi = s.nif
LEFT JOIN clientRisk cr ON cr.clientFk = c.id
LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id
LEFT JOIN bankEntity be ON be.id = sa.bankEntityFk
LEFT JOIN country co ON co.id = be.countryFk
AND cr.companyFk = vp.companyFk;
DROP TEMPORARY TABLE tOpeningBalances;
DROP TEMPORARY TABLE tPendingDuedates;
DROP TEMPORARY TABLE tRowsToDelete;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -0,0 +1,42 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`creditInsurance_getRisk`()
BEGIN
/**
* Devuelve el riesgo de los clientes que estan asegurados
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.client_list
(PRIMARY KEY (Id_Cliente))
ENGINE = MEMORY
SELECT * FROM (
SELECT cc.client Id_Cliente, ci.grade
FROM creditClassification cc
JOIN creditInsurance ci ON cc.id = ci.creditClassification
WHERE dateEnd IS NULL
ORDER BY ci.creationDate DESC
LIMIT 10000000000000000000) t1
GROUP BY Id_Cliente;
CALL vn2008.risk_vs_client_list(util.VN_CURDATE());
SELECT
c.id,
c.name,
c.credit clientCredit,
c.creditInsurance solunion,
CAST(r.risk AS DECIMAL(10,0)) risk,
CAST(c.creditInsurance - r.risk AS DECIMAL(10,0)) riskAlive,
cac.invoiced billedAnnually,
c.dueDay,
ci.grade,
c2.country
FROM tmp.client_list ci
LEFT JOIN tmp.risk r ON r.Id_Cliente = ci.Id_Cliente
JOIN client c ON c.id = ci.Id_Cliente
JOIN bs.clientAnnualConsumption cac ON c.id = cac.clientFk
JOIN country c2 ON c2.id = c.countryFk
GROUP BY c.id;
DROP TEMPORARY TABLE IF EXISTS tmp.risk;
DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
END$$
DELIMITER ;

View File

@ -0,0 +1,22 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_checkBooked`(
vSelf INT
)
BEGIN
/**
* Comprueba si una entrada está contabilizada,
* y si lo está retorna un throw.
*
* @param vSelf Id de entrada
*/
DECLARE vIsBooked BOOL;
SELECT isBooked INTO vIsBooked
FROM `entry`
WHERE id = vSelf;
IF vIsBooked THEN
CALL util.throw('Entry is already booked');
END IF;
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

@ -10,20 +10,15 @@ BEGIN
* @param vInvoiceInFk Id de factura recibida * @param vInvoiceInFk Id de factura recibida
*/ */
DECLARE vRate DOUBLE DEFAULT 1; DECLARE vRate DOUBLE DEFAULT 1;
DECLARE vDated DATE;
DECLARE vExpenseFk VARCHAR(10); DECLARE vExpenseFk VARCHAR(10);
SELECT MAX(rr.dated) INTO vDated SELECT `value` INTO vRate
FROM referenceRate rr FROM referenceRate rr
JOIN invoiceIn ii ON ii.id = vInvoiceInFk JOIN invoiceIn ii ON ii.id = vInvoiceInFk
WHERE rr.dated <= ii.issued WHERE rr.dated <= ii.issued
AND rr.currencyFk = ii.currencyFk; AND rr.currencyFk = ii.currencyFk
ORDER BY dated DESC
IF vDated THEN LIMIT 1;
SELECT `value` INTO vRate
FROM referenceRate
WHERE dated = vDated;
END IF;
DELETE FROM invoiceInTax WHERE invoiceInFk = vInvoiceInFk; DELETE FROM invoiceInTax WHERE invoiceInFk = vInvoiceInFk;

View File

@ -34,16 +34,22 @@ BEGIN
-- Rellena la tabla tmp.errorsByChecker con fallos de revisores -- Rellena la tabla tmp.errorsByChecker con fallos de revisores
CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByChecker CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByChecker
ENGINE = MEMORY ENGINE = MEMORY
SELECT st.workerFk, WITH rankedWorkers AS (
COUNT(t.id) errors SELECT sm.id,
FROM saleMistake sm st.workerFk,
JOIN saleTracking st ON sm.saleFk = st.saleFk ROW_NUMBER() OVER(PARTITION BY sm.id ORDER BY s2.`order`) rnk
JOIN `state` s2 ON s2.id = st.stateFk FROM vn.saleMistake sm
JOIN sale s ON s.id = sm.saleFk JOIN vn.saleTracking st ON sm.saleFk = st.saleFk
JOIN ticket t on t.id = s.ticketFk JOIN vn.`state` s2 ON s2.id = st.stateFk
WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) JOIN vn.sale s ON s.id = sm.saleFk
AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') JOIN vn.ticket t ON t.id = s.ticketFk
GROUP BY st.workerFk; WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
AND s2.code IN ('OK', 'PREVIOUS_PREPARATION', 'PREPARED', 'CHECKED')
)
SELECT workerFk, COUNT(*) errors
FROM rankedWorkers
WHERE rnk = 1
GROUP BY workerFk;
-- Rellena la tabla tmp.expeditionErrors con fallos de expediciones -- Rellena la tabla tmp.expeditionErrors con fallos de expediciones
CREATE OR REPLACE TEMPORARY TABLE tmp.expeditionErrors CREATE OR REPLACE TEMPORARY TABLE tmp.expeditionErrors

View File

@ -46,6 +46,7 @@ BEGIN
JOIN parking p ON p.id = sh.parkingFk JOIN parking p ON p.id = sh.parkingFk
JOIN tmp.productionBuffer pb ON pb.ticketFk = s.ticketFk JOIN tmp.productionBuffer pb ON pb.ticketFk = s.ticketFk
JOIN agencyMode am ON am.id = pb.agencyModeFk JOIN agencyMode am ON am.id = pb.agencyModeFk
JOIN agency a ON a .id = am.agencyFk
LEFT JOIN routesMonitor rm ON rm.routeFk = pb.routeFk LEFT JOIN routesMonitor rm ON rm.routeFk = pb.routeFk
LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk
@ -60,6 +61,7 @@ BEGIN
AND ((rm.bufferFk AND rm.isPickingAllowed) AND ((rm.bufferFk AND rm.isPickingAllowed)
OR am.code = 'REC_ALG') OR am.code = 'REC_ALG')
AND pb.shipped = vDated AND pb.shipped = vDated
AND a.isOwn
GROUP BY s.id GROUP BY s.id
ORDER BY etd; ORDER BY etd;

View File

@ -106,7 +106,7 @@ BEGIN
price) price)
SELECT vTicketFk, SELECT vTicketFk,
vNewItemFk, vNewItemFk,
CEIL(vQuantity / vRoundQuantity) * vRoundQuantity, CONCAT('+ ',i.longName), CEIL(vQuantity / vRoundQuantity) * vRoundQuantity, CONCAT('+ ', i.name),
vFinalPrice vFinalPrice
FROM vn.item i FROM vn.item i
WHERE id = vNewItemFk; WHERE id = vNewItemFk;

View File

@ -1,31 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`solunionRiskRequest`()
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
CREATE TEMPORARY TABLE tmp.client_list
(PRIMARY KEY (Id_Cliente))
ENGINE = MEMORY
SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc
JOIN vn.creditInsurance ci ON cc.id = ci.creditClassification
WHERE dateEnd IS NULL
ORDER BY ci.creationDate DESC
LIMIT 10000000000000000000) t1 GROUP BY Id_Cliente;
CALL vn2008.risk_vs_client_list(util.VN_CURDATE());
SELECT
c.Id_Cliente, c.Cliente, c.Credito credito_vn, c.creditInsurance solunion, cast(r.risk as DECIMAL(10,0)) riesgo_vivo,
cast(c.creditInsurance - r.risk as decimal(10,0)) margen_vivo,
f.Consumo consumo_anual, c.Vencimiento, ci.grade
FROM
vn2008.Clientes c
JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente
JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente
JOIN bi.facturacion_media_anual f ON c.Id_Cliente = f.Id_Cliente
GROUP BY Id_cliente;
DROP TEMPORARY TABLE IF EXISTS tmp.risk;
DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
END$$
DELIMITER ;

View File

@ -1,55 +1,10 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketClon`(vTicketFk INT, vNewShipped DATE) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketClon`(vTicketFk INT, vNewShipped DATE)
BEGIN BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE vNewTicketFk INT;
DECLARE vOldSaleFk INT;
DECLARE vNewSaleFk INT;
DECLARE cur1 CURSOR FOR
SELECT id
FROM vn.sale
WHERE ticketFk = vTicketFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET vNewShipped = IFNULL(vNewShipped, util.VN_CURDATE());
CALL vn.ticket_Clone(vTicketFk, vNewTicketFk);
UPDATE vn.ticket
SET landed = TIMESTAMPADD(DAY, DATEDIFF(vNewShipped, shipped), landed),
shipped = vNewShipped
WHERE id = vNewTicketFk;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO vOldSaleFk;
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed)
SELECT vNewTicketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed
FROM vn.sale
WHERE id = vOldSaleFk;
SELECT max(id) INTO vNewSaleFk
FROM vn.sale
WHERE ticketFk = vNewTicketFk;
INSERT INTO vn.saleComponent(saleFk, componentFk, value, isGreuge)
SELECT vNewSaleFk, componentFk, value, isGreuge
FROM vn.saleComponent
WHERE saleFk = vOldSaleFk;
END LOOP;
CLOSE cur1; DECLARE vNewTicketFk INT;
CALL ticket_cloneAll(vTicketFk, vNewShipped, TRUE, vNewTicketFk);
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -0,0 +1,55 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_cloneAll`(vTicketFk INT, vNewShipped DATE, vWithWarehouse BOOLEAN, OUT vNewTicketFk INT)
BEGIN
DECLARE vDone BOOLEAN DEFAULT FALSE;
DECLARE vOldSaleFk INT;
DECLARE vNewSaleFk INT;
DECLARE cur1 CURSOR FOR
SELECT id
FROM sale
WHERE ticketFk = vTicketFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vNewShipped = IFNULL(vNewShipped, util.VN_CURDATE());
CALL ticket_Clone(vTicketFk, vNewTicketFk);
UPDATE ticket
SET landed = TIMESTAMPADD(DAY, DATEDIFF(vNewShipped, shipped), landed),
shipped = vNewShipped,
warehouseFk = IF(vWithWarehouse, warehouseFk, NULL)
WHERE id = vNewTicketFk;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO vOldSaleFk;
IF vDone THEN
LEAVE read_loop;
END IF;
INSERT INTO sale(ticketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed)
SELECT vNewTicketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed
FROM sale
WHERE id = vOldSaleFk;
SELECT max(id) INTO vNewSaleFk
FROM sale
WHERE ticketFk = vNewTicketFk;
INSERT INTO saleComponent(saleFk, componentFk, value, isGreuge)
SELECT vNewSaleFk, componentFk, value, isGreuge
FROM saleComponent
WHERE saleFk = vOldSaleFk;
END LOOP;
CLOSE cur1;
END$$
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

@ -3,6 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`buy_beforeDelete`
BEFORE DELETE ON `buy` BEFORE DELETE ON `buy`
FOR EACH ROW FOR EACH ROW
BEGIN BEGIN
CALL entry_checkBooked(OLD.entryFk);
IF OLD.printedStickers <> 0 THEN IF OLD.printedStickers <> 0 THEN
CALL util.throw("it is not possible to delete buys with printed labels "); CALL util.throw("it is not possible to delete buys with printed labels ");
END IF; END IF;

View File

@ -9,17 +9,26 @@ 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;
END IF; END IF;
CALL entry_checkBooked(NEW.entryFk);
IF NEW.printedStickers <> 0 THEN IF NEW.printedStickers <> 0 THEN
CALL util.throw('it is not possible to create buy lines with printedstickers other than 0'); CALL util.throw('it is not possible to create buy lines with printedstickers other than 0');
END IF; END IF;
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,11 +7,13 @@ 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;
END IF; END IF;
CALL entry_checkBooked(OLD.entryFk);
SET NEW.editorFk = account.myUser_getId(); SET NEW.editorFk = account.myUser_getId();
SELECT defaultEntry INTO vDefaultEntry SELECT defaultEntry INTO vDefaultEntry
@ -65,6 +67,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

@ -3,6 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`entry_beforeDelete`
BEFORE DELETE ON `entry` BEFORE DELETE ON `entry`
FOR EACH ROW FOR EACH ROW
BEGIN BEGIN
CALL entry_checkBooked(OLD.id);
DELETE FROM buy WHERE entryFk = OLD.id; DELETE FROM buy WHERE entryFk = OLD.id;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -6,9 +6,13 @@ BEGIN
DECLARE vIsVirtual BOOL; DECLARE vIsVirtual BOOL;
DECLARE vPrintedCount INT; DECLARE vPrintedCount INT;
DECLARE vHasDistinctWarehouses BOOL; DECLARE vHasDistinctWarehouses BOOL;
IF NEW.isBooked = OLD.isBooked THEN
CALL entry_checkBooked(OLD.id);
END IF;
SET NEW.editorFk = account.myUser_getId(); SET NEW.editorFk = account.myUser_getId();
IF NOT (NEW.travelFk <=> OLD.travelFk) THEN IF NOT (NEW.travelFk <=> OLD.travelFk) THEN
IF NEW.travelFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.travelFk) THEN IF NEW.travelFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.travelFk) THEN

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

@ -12,5 +12,5 @@ FROM (
`pc`.`id` = `b`.`workerBusinessProfessionalCategoryFk` `pc`.`id` = `b`.`workerBusinessProfessionalCategoryFk`
) )
) )
WHERE `pc`.`name` = 'Aux ventas' WHERE `pc`.`description` = 'Aux ventas'
GROUP BY `b`.`workerFk` GROUP BY `b`.`workerFk`

View File

@ -1,61 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`add_awb_component`(IN vAwbFk SMALLINT)
BEGIN
DECLARE vShipped DATE;
DECLARE vHasStems BOOLEAN;
SELECT t.shipped, IF(a.stems, TRUE, FALSE)
INTO vShipped, vHasStems
FROM vn.travel t
JOIN vn.awb a ON a.id = t.awbFk
WHERE awbFk = vAwbFk
LIMIT 1;
INSERT IGNORE INTO awb_component (awb_id,Id_Proveedor,awb_component_type_id,awb_role_id,awb_unit_id,value,Id_Moneda)
SELECT id, Id_Proveedor, awb_component_type_id, awb_role_id,awb_unit_id, LEAST(GREATEST(value1, IFNULL(min_value, value1)), IFNULL(max_value, value1)), Id_Moneda
FROM (
SELECT a.id,
IFNULL(act.carguera_id,
CASE awb_role_id
WHEN 1 THEN a.carguera_id
WHEN 2 THEN a.transitario_id
WHEN 3 THEN f.airline_id
END
) Id_Proveedor,
act.awb_component_type_id,
act.awb_role_id,
act.awb_unit_id,
value *
CASE awb_unit_id
WHEN '1000Tj-20' THEN ((CAST(stems AS SIGNED) - 20000)/1000) + (min_value / value)
WHEN '1000Tj-10' THEN ((CAST(stems AS SIGNED) - 10000)/1000) + (min_value / value)
WHEN '100GW' THEN peso/100
WHEN 'AWB' THEN 1 -- No action
WHEN 'FB' THEN hb/2
WHEN 'GW' THEN peso
WHEN 'TW' THEN GREATEST(peso,volume_weight)
WHEN 'PN' THEN LEAST(90, value + a.propertyNumber * 10)
END value1,
value,
act.Id_Moneda,
act.min_value,
act.max_value
FROM awb a
JOIN flight f ON f.flight_id = a.flight_id
LEFT JOIN awb_component_template act ON
((IFNULL(act.carguera_id, a.carguera_id) = a.carguera_id AND awb_role_id = 1)
OR (IFNULL(act.carguera_id, a.transitario_id) = a.transitario_id AND awb_role_id = 2)
OR (IFNULL(act.airline_id, f.airline_id) = f.airline_id AND awb_role_id = 3)
OR (awb_role_id = 4))
AND IFNULL(act.airport_out, f.airport_out) = f.airport_out
AND IFNULL(act.airport_in, f.airport_in) = f.airport_in
AND IFNULL(act.airline_id, f.airline_id) = f.airline_id
AND INSTR(IFNULL(act.days, WEEKDAY(vShipped) + 1),WEEKDAY(vShipped) + 1)
JOIN awb_component_type acty ON acty.awb_component_type_id = act.awb_component_type_id
WHERE a.id = vAwbFk AND Fecha <= vShipped
AND (vHasStems = TRUE OR acty.hasStems)
ORDER BY Fecha DESC, act.days DESC LIMIT 10000000000000000000
) t;
END$$
DELIMITER ;

View File

@ -1,50 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`agencyModeImbalance`(vStarted DATE, vEnded DATE)
BEGIN
/**
* Devuelve el valor de los precios teorico, practico de las agencias
* y si ademas es de mrw lo compara con su fichero previamente procesado
*
* @param vEktFk Identificador de edi.ekt
*/
DECLARE vEndedDayEnd DATETIME;
SET vEndedDayEnd = util.dayEnd(vEnded);
SELECT t.id ticketFk,t.addressFk,
CAST(v.amount AS DECIMAL (10,2)) AS VN,
CAST(v.amount - e.shipping_charge AS DECIMAL (10,2)) AS Difer,
CAST(mrwPrice AS DECIMAL (10,2)) mrwPrice,
CAST(e.shipping_charge - mrwPrice AS DECIMAL (10,2)) mrwDifference,
CAST(e.shipping_charge AS DECIMAL (10,2)) AS teorico,
CAST(e.extraCharge AS DECIMAL (10,2)) AS extraCharge,
t.packages, t.clientFk,
t.zoneFk, a.provinceFk, mrwCount
FROM vn.ticket t
LEFT JOIN
(SELECT ticketFk, SUM(amount) amount, fc.shipped
FROM vn.sale_freightComponent fc
JOIN vn.ticket t ON t.id = fc.ticketFk
JOIN tmp.agencyMode am ON am.agencyModeFk = t.agencyModeFk
WHERE fc.shipped BETWEEN vStarted AND vEndedDayEnd
GROUP BY ticketFk) v ON t.id = v.ticketFk
LEFT JOIN (SELECT t.id,
SUM(t.zonePrice) shipping_charge,
SUM(IFNULL(aex.price,0)) extraCharge
FROM vn.ticket t
LEFT JOIN vn.expedition e ON e.ticketFk = t.id
LEFT JOIN vn.packaging p ON p.id = e.packagingFk
JOIN tmp.agencyMode amc ON amc.agencyModeFk = t.agencyModeFk
JOIN vn.agencyMode am ON am.id = amc.agencyModeFk
LEFT JOIN vn.agencyExtraCharge aex ON p.width+p.depth+p.height BETWEEN aex.sizeMin AND aex.sizeMax AND aex.agencyFk = am.agencyFk
WHERE t.shipped BETWEEN vStarted AND vEndedDayEnd
GROUP BY t.id
) e ON t.id = e.id
LEFT JOIN (SELECT ticketFk, SUM(price) mrwPrice, COUNT(*) mrwCount
FROM vn.mrw
GROUP BY ticketFk) mrw ON mrw.ticketFk = t.id
JOIN vn.address a ON a.id = t.addressFk
JOIN tmp.agencyMode am ON am.agencyModeFk = t.agencyModeFk
WHERE t.shipped BETWEEN vStarted AND vEndedDayEnd;
END$$
DELIMITER ;

View File

@ -1,91 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`historico_absoluto`(IN idART INT, IN wh INT, IN datfecha DATETIME)
BEGIN
DECLARE inv_calculado INT;
DECLARE inv INT;
DECLARE today DATETIME;
DECLARE fecha_inv DATETIME;
SET today = util.VN_CURDATE();
CREATE OR REPLACE TEMPORARY TABLE historico_pasado
SELECT *
FROM (
SELECT TR.landing Fecha,
C.Cantidad Entrada,
NULL Salida,
(TR.received != FALSE) OK,
P.Proveedor Alias,
E.Referencia Referencia,
E.Id_Entrada id,
TR.delivered F5
FROM Compres C -- mirar perque no entra en received
INNER JOIN Entradas E USING (Id_Entrada)
INNER JOIN travel TR ON TR.id = E.travel_id
INNER JOIN Proveedores P USING (Id_Proveedor)
WHERE TR.landing >= '2001-01-01'
AND Id_proveedor <> 4
AND wh IN (TR.warehouse_id , 0)
AND C.Id_Article = idART
AND E.Inventario = 0
AND E.Redada = 0
UNION ALL
SELECT TR.shipment Fecha,
NULL Entrada,
C.Cantidad Salida,
TR.delivered OK,
P.Proveedor Alias,
E.Referencia Referencia,
E.Id_Entrada id,
TR.delivered F5
FROM Compres C
INNER JOIN Entradas E USING (Id_Entrada)
INNER JOIN travel TR ON TR.id = E.travel_id
INNER JOIN Proveedores P USING (Id_Proveedor)
WHERE TR.shipment >= '2001-01-01'
AND wh = TR.warehouse_id_out
AND Id_Proveedor <> 4
AND C.Id_Article = idART
AND E.Inventario = 0
AND E.Redada = 0
UNION ALL
SELECT T.Fecha Fecha,
NULL Entrada,
M.Cantidad Salida,
(M.OK <> 0 OR T.Etiquetasemitidas <> 0 OR T.Factura IS NOT NULL) OK,
T.Alias Alias,
T.Factura Referencia,
T.Id_Ticket,
T.PedidoImpreso
FROM Movimientos M
INNER JOIN Tickets T USING (Id_Ticket)
JOIN Clientes C ON C.Id_Cliente = T.Id_Cliente
WHERE T.Fecha >= '2001-01-01'
AND M.Id_Article = idART
AND wh IN (T.warehouse_id , 0)
) t1
ORDER BY Fecha, Entrada DESC, OK DESC;
SELECT sum(Entrada) - sum(Salida) INTO inv_calculado
FROM historico_pasado
WHERE Fecha < datfecha;
SELECT p1.*, NULL v_virtual
FROM(
SELECT datfecha Fecha,
inv_calculado Entrada,
NULL Salida,
1 OK,
'Inventario calculado' Alias,
'' Referencia, 0 id,
1 F5
UNION ALL
SELECT *
FROM historico_pasado
WHERE Fecha >= datfecha
) p1;
DROP TEMPORARY TABLE historico_pasado;
END$$
DELIMITER ;

View File

@ -1,206 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`historico_multiple`(IN vItemFk INT)
BEGIN
DECLARE vDateInventory DATETIME;
SELECT Fechainventario INTO vDateInventory FROM tblContadores;
SET @a = 0;
DROP TEMPORARY TABLE IF EXISTS hm1;
CREATE TEMPORARY TABLE hm1
SELECT DATE(Fecha) as Fecha,
Entrada,
Salida,
OK,
Referencia,
Historia.id,
wh,
`name` as wh_name
FROM
( SELECT TR.landing as Fecha,
C.Cantidad as Entrada,
NULL as Salida,
IF(warehouse_id = 44, 1, warehouse_id) as wh,
(TR.received != FALSE) as OK,
E.Referencia as Referencia,
E.Id_Entrada as id
FROM Compres C
INNER JOIN Entradas E USING (Id_Entrada)
INNER JOIN travel TR ON TR.id = E.travel_id
WHERE TR.landing >= vDateInventory
AND C.Id_Article = vItemFk
AND E.Redada = 0
AND C.Cantidad <> 0
UNION ALL
SELECT TR.shipment as Fecha,
NULL as Entrada,
C.Cantidad as Salida,
warehouse_id_out as wh,
TR.delivered as OK,
E.Referencia as Referencia,
E.Id_Entrada as id
FROM Compres C
INNER JOIN Entradas E USING (Id_Entrada)
INNER JOIN travel TR ON TR.id = E.travel_id
WHERE TR.shipment >= vDateInventory
AND C.Id_Article = vItemFk
AND E.Redada = 0
AND C.Cantidad <> 0
UNION ALL
SELECT T.Fecha as Fecha,
NULL as Entrada,
M.Cantidad as Salida,
warehouse_id as wh,
(M.OK <> 0 OR T.Etiquetasemitidas <> 0 OR T.Factura IS NOT NULL) as OK,
T.Factura as Referencia,
T.Id_Ticket as id
FROM Movimientos M
INNER JOIN Tickets T USING (Id_Ticket)
WHERE T.Fecha >= vDateInventory
AND M.Id_Article = vItemFk
) AS Historia
INNER JOIN warehouse ON warehouse.id = Historia.wh
ORDER BY Fecha, Entrada DESC, OK DESC;
DROP TEMPORARY TABLE IF EXISTS hm2;
DROP TEMPORARY TABLE IF EXISTS hm3;
DROP TEMPORARY TABLE IF EXISTS hm4;
DROP TEMPORARY TABLE IF EXISTS hm5;
DROP TEMPORARY TABLE IF EXISTS hm6;
DROP TEMPORARY TABLE IF EXISTS hm7;
DROP TEMPORARY TABLE IF EXISTS hm8;
CREATE TEMPORARY TABLE hm2 SELECT * FROM hm1 WHERE wh = 19;
CREATE TEMPORARY TABLE hm3 SELECT * FROM hm1 WHERE wh = 7;
CREATE TEMPORARY TABLE hm4 SELECT * FROM hm1 WHERE wh = 60;
CREATE TEMPORARY TABLE hm5 SELECT * FROM hm1 WHERE wh = 5;
CREATE TEMPORARY TABLE hm6 SELECT * FROM hm1 WHERE wh = 17;
CREATE TEMPORARY TABLE hm7 SELECT * FROM hm1 WHERE wh = 37;
CREATE TEMPORARY TABLE hm8 SELECT * FROM hm1 WHERE wh = 55;
SELECT * FROM
(
SELECT Fecha, Entrada as BOGEntrada, Salida as BOGSalida, OK as BOGOK, Referencia as BOGReferencia, id as BOGid,
NULL AS VNHEntrada, NULL AS VNHSalida, NULL AS VNHOK, NULL AS VNHReferencia, NULL AS VNHid,
NULL AS ALGEntrada, NULL AS ALGSalida, NULL AS ALGOK, NULL AS ALGReferencia, NULL AS ALGid,
NULL AS MADEntrada, NULL AS MADSalida, NULL AS MADOK, NULL AS MADReferencia, NULL AS MADid,
NULL AS MCFEntrada, NULL AS MCFSalida, NULL AS MCFOK, NULL AS MCFReferencia, NULL AS MCFid,
NULL AS VILEntrada, NULL AS VILSalida, NULL AS VILOK, NULL AS VILReferencia, NULL AS VILid,
NULL AS BAREntrada, NULL AS BARSalida, NULL AS BAROK, NULL AS BARReferencia, NULL AS BARid
FROM hm2
UNION ALL
SELECT Fecha
, NULL, NULL, NULL, NULL, NULL
,Entrada, Salida, OK, Referencia, id
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
FROM hm3
UNION ALL
SELECT Fecha
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, Entrada, Salida, OK, Referencia, id
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
FROM hm4
UNION ALL
SELECT Fecha
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, Entrada, Salida, OK, Referencia, id
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
FROM hm5
UNION ALL
SELECT Fecha
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, Entrada, Salida, OK, Referencia, id
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
FROM hm6
UNION ALL
SELECT Fecha
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, Entrada, Salida, OK, Referencia, id
, NULL, NULL, NULL, NULL, NULL
FROM hm7
UNION ALL
SELECT Fecha
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, NULL, NULL, NULL, NULL, NULL
, Entrada, Salida, OK, Referencia, id
FROM hm8
) sub
ORDER BY Fecha, BOGEntrada IS NULL, VNHEntrada IS NULL, ALGEntrada IS NULL, MADEntrada IS NULL, MCFEntrada IS NULL, VILEntrada IS NULL, BAREntrada IS 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,14 @@
CREATE SCHEMA IF NOT EXISTS `floranet`;
CREATE ROLE IF NOT EXISTS 'floranet' ;
GRANT Create temporary tables ON floranet.* TO 'floranet';
GRANT Execute ON floranet.* TO 'floranet';
GRANT Lock tables ON floranet.* TO 'floranet';
CREATE USER IF NOT EXISTS 'floranet'@'%';
GRANT floranet TO floranet@'%';

View File

@ -0,0 +1,61 @@
CREATE OR REPLACE TABLE floranet.`builder` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`itemFk` int(11) NOT NULL,
`elementFk` int(11) NOT NULL,
`quantity` int(10) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
KEY `builder_FK` (`itemFk`),
KEY `builder_FK_1` (`elementFk`),
CONSTRAINT `builder_FK` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Links handmade products with their elements';
CREATE OR REPLACE TABLE floranet.`element` (
`itemFk` int(11) NOT NULL,
`typeFk` smallint(5) unsigned DEFAULT NULL,
`size` int(11) DEFAULT NULL,
`inkFk` char(3) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`originFk` tinyint(2) unsigned DEFAULT NULL,
`name` varchar(30) DEFAULT NULL,
`quantity` int(11) NOT NULL DEFAULT 1,
PRIMARY KEY (`itemFk`),
KEY `element_FK` (`itemFk`),
KEY `element_FK_1` (`typeFk`),
KEY `element_FK_2` (`inkFk`),
KEY `element_FK_3` (`originFk`),
CONSTRAINT `element_FK` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `element_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `vn`.`itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `element_FK_2` FOREIGN KEY (`inkFk`) REFERENCES `vn`.`ink` (`id`) ON UPDATE CASCADE,
CONSTRAINT `element_FK_3` FOREIGN KEY (`originFk`) REFERENCES `vn`.`origin` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Filtro para localizar posibles items que coincidan con la descripción';
ALTER TABLE floranet.builder ADD CONSTRAINT `builder_FK_1` FOREIGN KEY (`elementFk`) REFERENCES `element` (`itemFk`) ON UPDATE CASCADE;
CREATE OR REPLACE TABLE floranet.catalogue
(id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
price DECIMAL(10,2) NOT NULL,
itemFk INT NOT NULL,
dated DATE,
postalCode VARCHAR(12),
`type` VARCHAR(50),
image VARCHAR(255),
description TEXT,
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
payed DATETIME,
FOREIGN KEY (itemFk) REFERENCES vn.item(id) ON DELETE RESTRICT ON UPDATE CASCADE);
CREATE OR REPLACE TABLE floranet.`order`
(id INT AUTO_INCREMENT PRIMARY KEY,
catalogueFk INT UNIQUE,
customerName VARCHAR(100),
email VARCHAR(100),
customerPhone VARCHAR(15),
message VARCHAR(255),
deliveryName VARCHAR(100),
address VARCHAR(200),
deliveryPhone VARCHAR(100),
isPaid BOOL NOT NULL DEFAULT FALSE,
payed DATETIME,
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (catalogueFk) REFERENCES catalogue(id) ON DELETE RESTRICT ON UPDATE CASCADE);

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,3 @@
-- Place your SQL code here

View File

@ -0,0 +1,22 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`multipleInventoryHistory`(
vItemFk INT)
BEGIN
DECLARE vDateInventory DATETIME;
SELECT inventoried INTO vDateInventory FROM config;
END$$
DELIMITER ;
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`absoluteInventoryHistory`(
vItemFk INT, vWarehouse INT, vDate DATETIME)
BEGIN
DECLARE vCalculatedInventory INT;
SET vCalculatedInventory = 0;
END$$
DELIMITER ;
GRANT EXECUTE ON PROCEDURE vn.absoluteInventoryHistory TO buyer;
GRANT EXECUTE ON PROCEDURE vn.multipleInventoryHistory TO buyer;

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,12 @@
CREATE TABLE floranet.`addressPostCode` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`addressFk` int(11) NOT NULL,
`postCode` varchar(30) NOT NULL,
`hoursInAdvance` int(10) unsigned NOT NULL DEFAULT 24,
`dayOfWeek` int(10) unsigned NOT NULL,
`deliveryCost` decimal(10,2) NOT NULL DEFAULT 0.00,
PRIMARY KEY (`id`),
UNIQUE KEY `addressPostCode_unique` (`postCode`,`addressFk`,`dayOfWeek`),
KEY `addressPostCode_address_FK` (`addressFk`),
CONSTRAINT `addressPostCode_address_FK` FOREIGN KEY (`addressFk`) REFERENCES `vn`.`address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Client''s address registered for floranet network';

View File

@ -0,0 +1,2 @@
INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
VALUES('Ticket', 'clone', 'WRITE', 'ALLOW', 'ROLE', 'administrative');

View File

@ -0,0 +1,3 @@
ALTER TABLE vn.professionalCategory DROP COLUMN dayBreak, DROP COLUMN `level`;
ALTER TABLE vn.professionalCategory
CHANGE name description varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL;

View File

@ -0,0 +1,3 @@
-- Place your SQL code here
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES('SupplierDms', '*', '*', 'ALLOW', 'ROLE', 'employee');

View File

@ -0,0 +1,10 @@
ALTER TABLE vn.specialPrice MODIFY COLUMN clientFk int(11) NULL;
ALTER TABLE vn.specialPrice ADD started date NOT NULL DEFAULT '2024-01-01';
ALTER TABLE vn.specialPrice ADD ended date NULL;
ALTER TABLE vn.specialPrice MODIFY COLUMN itemFk int(11) NOT NULL;
ALTER TABLE vn.specialPrice MODIFY COLUMN value DECIMAL(10,2) NOT NULL;
ALTER TABLE vn.`specialPrice`
ADD CONSTRAINT `check_date_range`
CHECK (`ended` IS NULL OR `ended` >= `started`);

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

@ -22,12 +22,4 @@ describe('Account Connections path', () => {
expect(firstResult).toContain(account); expect(firstResult).toContain(account);
}); });
it('should kill this connection and then get redirected to the login page', async() => {
await page.waitToClick(selectors.accountConnections.deleteFirstConnection);
await page.waitToClick(selectors.globalItems.acceptButton);
const message = await page.waitForSnackbar();
expect(message.text).toContain('Your session has expired, please login again');
});
}); });

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

@ -14,7 +14,7 @@ class File {
*/ */
getPath(dmsUrl) { getPath(dmsUrl) {
const serializedParams = this.$httpParamSerializer({ const serializedParams = this.$httpParamSerializer({
access_token: this.vnToken.token access_token: this.vnToken.tokenMultimedia
}); });
return `${dmsUrl}?${serializedParams}`; return `${dmsUrl}?${serializedParams}`;

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

@ -15,7 +15,7 @@ class Report {
*/ */
show(path, params) { show(path, params) {
params = Object.assign({ params = Object.assign({
access_token: this.vnToken.token access_token: this.vnToken.tokenMultimedia
}, params); }, params);
const serializedParams = this.$httpParamSerializer(params); const serializedParams = this.$httpParamSerializer(params);
const query = serializedParams ? `?${serializedParams}` : ''; const query = serializedParams ? `?${serializedParams}` : '';

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

@ -1,351 +1,353 @@
{ {
"Phone format is invalid": "El formato del teléfono no es correcto", "Phone format is invalid": "El formato del teléfono no es correcto",
"You are not allowed to change the credit": "No tienes privilegios para modificar el crédito", "You are not allowed to change the credit": "No tienes privilegios para modificar el crédito",
"Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia", "Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia",
"The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado", "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado",
"Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado", "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado",
"Can't be blank": "No puede estar en blanco", "Can't be blank": "No puede estar en blanco",
"Invalid TIN": "NIF/CIF inválido", "Invalid TIN": "NIF/CIF inválido",
"TIN must be unique": "El NIF/CIF debe ser único", "TIN must be unique": "El NIF/CIF debe ser único",
"A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web", "A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web",
"Is invalid": "Es inválido", "Is invalid": "Es inválido",
"Quantity cannot be zero": "La cantidad no puede ser cero", "Quantity cannot be zero": "La cantidad no puede ser cero",
"Enter an integer different to zero": "Introduce un entero distinto de cero", "Enter an integer different to zero": "Introduce un entero distinto de cero",
"Package cannot be blank": "El embalaje no puede estar en blanco", "Package cannot be blank": "El embalaje no puede estar en blanco",
"The company name must be unique": "La razón social debe ser única", "The company name must be unique": "La razón social debe ser única",
"Invalid email": "Correo electrónico inválido", "Invalid email": "Correo electrónico inválido",
"The IBAN does not have the correct format": "El IBAN no tiene el formato correcto", "The IBAN does not have the correct format": "El IBAN no tiene el formato correcto",
"That payment method requires an IBAN": "El método de pago seleccionado requiere un IBAN", "That payment method requires an IBAN": "El método de pago seleccionado requiere un IBAN",
"That payment method requires a BIC": "El método de pago seleccionado requiere un BIC", "That payment method requires a BIC": "El método de pago seleccionado requiere un BIC",
"State cannot be blank": "El estado no puede estar en blanco", "State cannot be blank": "El estado no puede estar en blanco",
"Worker cannot be blank": "El trabajador no puede estar en blanco", "Worker cannot be blank": "El trabajador no puede estar en blanco",
"Cannot change the payment method if no salesperson": "No se puede cambiar la forma de pago si no hay comercial asignado", "Cannot change the payment method if no salesperson": "No se puede cambiar la forma de pago si no hay comercial asignado",
"can't be blank": "El campo no puede estar vacío", "can't be blank": "El campo no puede estar vacío",
"Observation type must be unique": "El tipo de observación no puede repetirse", "Observation type must be unique": "El tipo de observación no puede repetirse",
"The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero", "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero",
"The grade must be similar to the last one": "El grade debe ser similar al último", "The grade must be similar to the last one": "El grade debe ser similar al último",
"Only manager can change the credit": "Solo el gerente puede cambiar el credito de este cliente", "Only manager can change the credit": "Solo el gerente puede cambiar el credito de este cliente",
"Name cannot be blank": "El nombre no puede estar en blanco", "Name cannot be blank": "El nombre no puede estar en blanco",
"Phone cannot be blank": "El teléfono no puede estar en blanco", "Phone cannot be blank": "El teléfono no puede estar en blanco",
"Period cannot be blank": "El periodo no puede estar en blanco", "Period cannot be blank": "El periodo no puede estar en blanco",
"Choose a company": "Selecciona una empresa", "Choose a company": "Selecciona una empresa",
"Se debe rellenar el campo de texto": "Se debe rellenar el campo de texto", "Se debe rellenar el campo de texto": "Se debe rellenar el campo de texto",
"Description should have maximum of 45 characters": "La descripción debe tener maximo 45 caracteres", "Description should have maximum of 45 characters": "La descripción debe tener maximo 45 caracteres",
"Cannot be blank": "El campo no puede estar en blanco", "Cannot be blank": "El campo no puede estar en blanco",
"The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero", "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero",
"Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco", "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco",
"Description cannot be blank": "Se debe rellenar el campo de texto", "Description cannot be blank": "Se debe rellenar el campo de texto",
"The price of the item changed": "El precio del artículo cambió", "The price of the item changed": "El precio del artículo cambió",
"The value should not be greater than 100%": "El valor no debe de ser mayor de 100%", "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%",
"The value should be a number": "El valor debe ser un numero", "The value should be a number": "El valor debe ser un numero",
"This order is not editable": "Esta orden no se puede modificar", "This order is not editable": "Esta orden no se puede modificar",
"You can't create an order for a frozen client": "No puedes crear una orden para un cliente congelado", "You can't create an order for a frozen client": "No puedes crear una orden para un cliente congelado",
"You can't create an order for a client that has a debt": "No puedes crear una orden para un cliente con deuda", "You can't create an order for a client that has a debt": "No puedes crear una orden para un cliente con deuda",
"is not a valid date": "No es una fecha valida", "is not a valid date": "No es una fecha valida",
"Barcode must be unique": "El código de barras debe ser único", "Barcode must be unique": "El código de barras debe ser único",
"The warehouse can't be repeated": "El almacén no puede repetirse", "The warehouse can't be repeated": "El almacén no puede repetirse",
"The tag or priority can't be repeated for an item": "El tag o prioridad no puede repetirse para un item", "The tag or priority can't be repeated for an item": "El tag o prioridad no puede repetirse para un item",
"The observation type can't be repeated": "El tipo de observación no puede repetirse", "The observation type can't be repeated": "El tipo de observación no puede repetirse",
"A claim with that sale already exists": "Ya existe una reclamación para esta línea", "A claim with that sale already exists": "Ya existe una reclamación para esta línea",
"You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo", "You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo",
"Warehouse cannot be blank": "El almacén no puede quedar en blanco", "Warehouse cannot be blank": "El almacén no puede quedar en blanco",
"Agency cannot be blank": "La agencia no puede quedar en blanco", "Agency cannot be blank": "La agencia no puede quedar en blanco",
"Not enough privileges to edit a client with verified data": "No tienes permisos para hacer cambios en un cliente con datos comprobados", "Not enough privileges to edit a client with verified data": "No tienes permisos para hacer cambios en un cliente con datos comprobados",
"This address doesn't exist": "Este consignatario no existe", "This address doesn't exist": "Este consignatario no existe",
"You must delete the claim id %d first": "Antes debes borrar la reclamación %d", "You must delete the claim id %d first": "Antes debes borrar la reclamación %d",
"You don't have enough privileges": "No tienes suficientes permisos", "You don't have enough privileges": "No tienes suficientes permisos",
"Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF", "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF",
"You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos básicos de una orden con artículos", "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos básicos de una orden con artículos",
"INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no está permitido el uso de la letra ñ", "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no está permitido el uso de la letra ñ",
"You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado", "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado",
"You can't create a ticket for an inactive client": "No puedes crear un ticket para un cliente inactivo", "You can't create a ticket for an inactive client": "No puedes crear un ticket para un cliente inactivo",
"Tag value cannot be blank": "El valor del tag no puede quedar en blanco", "Tag value cannot be blank": "El valor del tag no puede quedar en blanco",
"ORDER_EMPTY": "Cesta vacía", "ORDER_EMPTY": "Cesta vacía",
"You don't have enough privileges to do that": "No tienes permisos para cambiar esto", "You don't have enough privileges to do that": "No tienes permisos para cambiar esto",
"NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT", "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT",
"Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido", "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido",
"Street cannot be empty": "Dirección no puede estar en blanco", "Street cannot be empty": "Dirección no puede estar en blanco",
"City cannot be empty": "Ciudad no puede estar en blanco", "City cannot be empty": "Ciudad no puede estar en blanco",
"Code cannot be blank": "Código no puede estar en blanco", "Code cannot be blank": "Código no puede estar en blanco",
"You cannot remove this department": "No puedes eliminar este departamento", "You cannot remove this department": "No puedes eliminar este departamento",
"The extension must be unique": "La extensión debe ser unica", "The extension must be unique": "La extensión debe ser unica",
"The secret can't be blank": "La contraseña no puede estar en blanco", "The secret can't be blank": "La contraseña no puede estar en blanco",
"We weren't able to send this SMS": "No hemos podido enviar el SMS", "We weren't able to send this SMS": "No hemos podido enviar el SMS",
"This client can't be invoiced": "Este cliente no puede ser facturado", "This client can't be invoiced": "Este cliente no puede ser facturado",
"You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa",
"This ticket can't be invoiced": "Este ticket no puede ser facturado", "This ticket can't be invoiced": "Este ticket no puede ser facturado",
"You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado",
"This ticket can not be modified": "Este ticket no puede ser modificado", "This ticket can not be modified": "Este ticket no puede ser modificado",
"The introduced hour already exists": "Esta hora ya ha sido introducida", "The introduced hour already exists": "Esta hora ya ha sido introducida",
"INFINITE_LOOP": "Existe una dependencia entre dos Jefes", "INFINITE_LOOP": "Existe una dependencia entre dos Jefes",
"The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas", "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas",
"NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros", "NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros",
"ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado", "ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado",
"The current ticket can't be modified": "El ticket actual no puede ser modificado", "The current ticket can't be modified": "El ticket actual no puede ser modificado",
"The current claim can't be modified": "La reclamación actual no puede ser modificada", "The current claim can't be modified": "La reclamación actual no puede ser modificada",
"The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas", "The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas",
"The sales do not exists": "La(s) línea(s) seleccionada(s) no existe(n)", "The sales do not exists": "La(s) línea(s) seleccionada(s) no existe(n)",
"Please select at least one sale": "Por favor selecciona al menos una linea", "Please select at least one sale": "Por favor selecciona al menos una linea",
"All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket", "All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket",
"NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", "NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada",
"This item doesn't exists": "El artículo no existe", "This item doesn't exists": "El artículo no existe",
"NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", "NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada",
"Extension format is invalid": "El formato de la extensión es inválido", "Extension format is invalid": "El formato de la extensión es inválido",
"Invalid parameters to create a new ticket": "Parámetros inválidos para crear un nuevo ticket", "Invalid parameters to create a new ticket": "Parámetros inválidos para crear un nuevo ticket",
"This item is not available": "Este artículo no está disponible", "This item is not available": "Este artículo no está disponible",
"This postcode already exists": "Este código postal ya existe", "This postcode already exists": "Este código postal ya existe",
"Concept cannot be blank": "El concepto no puede quedar en blanco", "Concept cannot be blank": "El concepto no puede quedar en blanco",
"File doesn't exists": "El archivo no existe", "File doesn't exists": "El archivo no existe",
"You don't have privileges to change the zone": "No tienes permisos para cambiar la zona o para esos parámetros hay más de una opción de envío, hable con las agencias", "You don't have privileges to change the zone": "No tienes permisos para cambiar la zona o para esos parámetros hay más de una opción de envío, hable con las agencias",
"This ticket is already on weekly tickets": "Este ticket ya está en tickets programados", "This ticket is already on weekly tickets": "Este ticket ya está en tickets programados",
"Ticket id cannot be blank": "El id de ticket no puede quedar en blanco", "Ticket id cannot be blank": "El id de ticket no puede quedar en blanco",
"Weekday cannot be blank": "El día de la semana no puede quedar en blanco", "Weekday cannot be blank": "El día de la semana no puede quedar en blanco",
"You can't delete a confirmed order": "No puedes borrar un pedido confirmado", "You can't delete a confirmed order": "No puedes borrar un pedido confirmado",
"The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto", "The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto",
"Invalid quantity": "Cantidad invalida", "Invalid quantity": "Cantidad invalida",
"This postal code is not valid": "Este código postal no es válido", "This postal code is not valid": "Este código postal no es válido",
"is invalid": "es inválido", "is invalid": "es inválido",
"The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto", "The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto",
"The department name can't be repeated": "El nombre del departamento no puede repetirse", "The department name can't be repeated": "El nombre del departamento no puede repetirse",
"This phone already exists": "Este teléfono ya existe", "This phone already exists": "Este teléfono ya existe",
"You cannot move a parent to its own sons": "No puedes mover un elemento padre a uno de sus hijos", "You cannot move a parent to its own sons": "No puedes mover un elemento padre a uno de sus hijos",
"You can't create a claim for a removed ticket": "No puedes crear una reclamación para un ticket eliminado", "You can't create a claim for a removed ticket": "No puedes crear una reclamación para un ticket eliminado",
"You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada", "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada",
"You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero", "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero",
"You should specify a date": "Debes especificar una fecha", "You should specify a date": "Debes especificar una fecha",
"You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fin", "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fin",
"Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fin", "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fin",
"You should mark at least one week day": "Debes marcar al menos un día de la semana", "You should mark at least one week day": "Debes marcar al menos un día de la semana",
"Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío",
"Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios",
"Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios", "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios",
"Deleted sales from ticket": "He eliminado las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}", "Deleted sales from ticket": "He eliminado las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}",
"Added sale to ticket": "He añadido la siguiente linea al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}", "Added sale to ticket": "He añadido la siguiente linea al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}",
"Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
"Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
"Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})", "Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})",
"Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})", "Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})",
"State": "Estado", "State": "Estado",
"regular": "normal", "regular": "normal",
"reserved": "reservado", "reserved": "reservado",
"Changed sale reserved state": "He cambiado el estado reservado de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Changed sale reserved state": "He cambiado el estado reservado de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
"Bought units from buy request": "Se ha comprado {{quantity}} unidades de [{{itemId}} {{concept}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})", "Bought units from buy request": "Se ha comprado {{quantity}} unidades de [{{itemId}} {{concept}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})",
"Deny buy request": "Se ha rechazado la petición de compra para el ticket id [{{ticketId}}]({{{url}}}). Motivo: {{observation}}", "Deny buy request": "Se ha rechazado la petición de compra para el ticket id [{{ticketId}}]({{{url}}}). Motivo: {{observation}}",
"MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} ({{clientId}})]({{{url}}}) a *{{credit}} €*", "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} ({{clientId}})]({{{url}}}) a *{{credit}} €*",
"Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})", "Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})",
"Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})", "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})",
"Change quantity": "{{concept}} cambia de {{oldQuantity}} a {{newQuantity}}", "Change quantity": "{{concept}} cambia de {{oldQuantity}} a {{newQuantity}}",
"Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", "Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*",
"Claim state has changed to": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *{{newState}}*", "Claim state has changed to": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *{{newState}}*",
"Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}",
"ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto",
"Distance must be lesser than 4000": "La distancia debe ser inferior a 4000", "Distance must be lesser than 4000": "La distancia debe ser inferior a 4000",
"This ticket is deleted": "Este ticket está eliminado", "This ticket is deleted": "Este ticket está eliminado",
"Unable to clone this travel": "No ha sido posible clonar este travel", "Unable to clone this travel": "No ha sido posible clonar este travel",
"This thermograph id already exists": "La id del termógrafo ya existe", "This thermograph id already exists": "La id del termógrafo ya existe",
"Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante", "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante",
"ORDER_ALREADY_CONFIRMED": "ORDEN YA CONFIRMADA", "ORDER_ALREADY_CONFIRMED": "ORDEN YA CONFIRMADA",
"Invalid password": "Invalid password", "Invalid password": "Invalid password",
"Password does not meet requirements": "La contraseña no cumple los requisitos", "Password does not meet requirements": "La contraseña no cumple los requisitos",
"Role already assigned": "Rol ya asignado", "Role already assigned": "Rol ya asignado",
"Invalid role name": "Nombre de rol no válido", "Invalid role name": "Nombre de rol no válido",
"Role name must be written in camelCase": "El nombre del rol debe escribirse en camelCase", "Role name must be written in camelCase": "El nombre del rol debe escribirse en camelCase",
"Email already exists": "El correo ya existe", "Email already exists": "El correo ya existe",
"User already exists": "El/La usuario/a ya existe", "User already exists": "El/La usuario/a ya existe",
"Absence change notification on the labour calendar": "Notificación de cambio de ausencia en el calendario laboral", "Absence change notification on the labour calendar": "Notificación de cambio de ausencia en el calendario laboral",
"Record of hours week": "Registro de horas semana {{week}} año {{year}} ", "Record of hours week": "Registro de horas semana {{week}} año {{year}} ",
"Created absence": "El empleado <strong>{{author}}</strong> ha añadido una ausencia de tipo '{{absenceType}}' a <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> para el día {{dated}}.", "Created absence": "El empleado <strong>{{author}}</strong> ha añadido una ausencia de tipo '{{absenceType}}' a <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> para el día {{dated}}.",
"Deleted absence": "El empleado <strong>{{author}}</strong> ha eliminado una ausencia de tipo '{{absenceType}}' a <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> del día {{dated}}.", "Deleted absence": "El empleado <strong>{{author}}</strong> ha eliminado una ausencia de tipo '{{absenceType}}' a <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> del día {{dated}}.",
"I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})", "I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})",
"I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})", "I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})",
"You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación", "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación",
"Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
"agencyModeFk": "Agencia", "agencyModeFk": "Agencia",
"clientFk": "Cliente", "clientFk": "Cliente",
"zoneFk": "Zona", "zoneFk": "Zona",
"warehouseFk": "Almacén", "warehouseFk": "Almacén",
"shipped": "F. envío", "shipped": "F. envío",
"landed": "F. entrega", "landed": "F. entrega",
"addressFk": "Consignatario", "addressFk": "Consignatario",
"companyFk": "Empresa", "companyFk": "Empresa",
"The social name cannot be empty": "La razón social no puede quedar en blanco", "The social name cannot be empty": "La razón social no puede quedar en blanco",
"The nif cannot be empty": "El NIF no puede quedar en blanco", "The nif cannot be empty": "El NIF no puede quedar en blanco",
"You need to fill sage information before you check verified data": "Debes rellenar la información de sage antes de marcar datos comprobados", "You need to fill sage information before you check verified data": "Debes rellenar la información de sage antes de marcar datos comprobados",
"ASSIGN_ZONE_FIRST": "Asigna una zona primero", "ASSIGN_ZONE_FIRST": "Asigna una zona primero",
"Amount cannot be zero": "El importe no puede ser cero", "Amount cannot be zero": "El importe no puede ser cero",
"Company has to be official": "Empresa inválida", "Company has to be official": "Empresa inválida",
"You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria", "You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria",
"Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas", "Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas",
"The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta", "The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta",
"New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*", "New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*",
"New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*", "New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*",
"Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío", "Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío",
"This BIC already exist.": "Este BIC ya existe.", "This BIC already exist.": "Este BIC ya existe.",
"That item doesn't exists": "Ese artículo no existe", "That item doesn't exists": "Ese artículo no existe",
"There's a new urgent ticket:": "Hay un nuevo ticket urgente:", "There's a new urgent ticket:": "Hay un nuevo ticket urgente:",
"Invalid account": "Cuenta inválida", "Invalid account": "Cuenta inválida",
"Compensation account is empty": "La cuenta para compensar está vacia", "Compensation account is empty": "La cuenta para compensar está vacia",
"This genus already exist": "Este genus ya existe", "This genus already exist": "Este genus ya existe",
"This specie already exist": "Esta especie ya existe", "This specie already exist": "Esta especie ya existe",
"Client assignment has changed": "He cambiado el comercial ~*\"<{{previousWorkerName}}>\"*~ por *\"<{{currentWorkerName}}>\"* del cliente [{{clientName}} ({{clientId}})]({{{url}}})", "Client assignment has changed": "He cambiado el comercial ~*\"<{{previousWorkerName}}>\"*~ por *\"<{{currentWorkerName}}>\"* del cliente [{{clientName}} ({{clientId}})]({{{url}}})",
"None": "Ninguno", "None": "Ninguno",
"The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada", "The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada",
"Cannot add more than one '1/2 day vacation'": "No puedes añadir más de un 'Vacaciones 1/2 dia'", "Cannot add more than one '1/2 day vacation'": "No puedes añadir más de un 'Vacaciones 1/2 dia'",
"This document already exists on this ticket": "Este documento ya existe en el ticket", "This document already exists on this ticket": "Este documento ya existe en el ticket",
"Some of the selected tickets are not billable": "Algunos de los tickets seleccionados no son facturables", "Some of the selected tickets are not billable": "Algunos de los tickets seleccionados no son facturables",
"You can't invoice tickets from multiple clients": "No puedes facturar tickets de multiples clientes", "You can't invoice tickets from multiple clients": "No puedes facturar tickets de multiples clientes",
"nickname": "nickname", "nickname": "nickname",
"INACTIVE_PROVIDER": "Proveedor inactivo", "INACTIVE_PROVIDER": "Proveedor inactivo",
"This client is not invoiceable": "Este cliente no es facturable", "This client is not invoiceable": "Este cliente no es facturable",
"serial non editable": "Esta serie no permite asignar la referencia", "serial non editable": "Esta serie no permite asignar la referencia",
"Max shipped required": "La fecha límite es requerida", "Max shipped required": "La fecha límite es requerida",
"Can't invoice to future": "No se puede facturar a futuro", "Can't invoice to future": "No se puede facturar a futuro",
"Can't invoice to past": "No se puede facturar a pasado", "Can't invoice to past": "No se puede facturar a pasado",
"This ticket is already invoiced": "Este ticket ya está facturado", "This ticket is already invoiced": "Este ticket ya está facturado",
"A ticket with an amount of zero can't be invoiced": "No se puede facturar un ticket con importe cero", "A ticket with an amount of zero can't be invoiced": "No se puede facturar un ticket con importe cero",
"A ticket with a negative base can't be invoiced": "No se puede facturar un ticket con una base negativa", "A ticket with a negative base can't be invoiced": "No se puede facturar un ticket con una base negativa",
"Global invoicing failed": "[Facturación global] No se han podido facturar algunos clientes", "Global invoicing failed": "[Facturación global] No se han podido facturar algunos clientes",
"Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes", "Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes",
"Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio", "Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio",
"You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito", "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito",
"You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas", "You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas",
"Amounts do not match": "Las cantidades no coinciden", "Amounts do not match": "Las cantidades no coinciden",
"The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'", "The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'",
"The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos", "The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos",
"You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días", "You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días",
"The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día", "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día",
"The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día", "The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día",
"You can not modify is pay method checked": "No se puede modificar el campo método de pago validado", "You can not modify is pay method checked": "No se puede modificar el campo método de pago validado",
"The account size must be exactly 10 characters": "El tamaño de la cuenta debe ser exactamente de 10 caracteres", "The account size must be exactly 10 characters": "El tamaño de la cuenta debe ser exactamente de 10 caracteres",
"Can't transfer claimed sales": "No puedes transferir lineas reclamadas", "Can't transfer claimed sales": "No puedes transferir lineas reclamadas",
"You don't have privileges to create refund": "No tienes permisos para crear un abono", "You don't have privileges to create refund": "No tienes permisos para crear un abono",
"The item is required": "El artículo es requerido", "The item is required": "El artículo es requerido",
"The agency is already assigned to another autonomous": "La agencia ya está asignada a otro autónomo", "The agency is already assigned to another autonomous": "La agencia ya está asignada a otro autónomo",
"date in the future": "Fecha en el futuro", "date in the future": "Fecha en el futuro",
"reference duplicated": "Referencia duplicada", "reference duplicated": "Referencia duplicada",
"This ticket is already a refund": "Este ticket ya es un abono", "This ticket is already a refund": "Este ticket ya es un abono",
"isWithoutNegatives": "Sin negativos", "isWithoutNegatives": "Sin negativos",
"routeFk": "routeFk", "routeFk": "routeFk",
"Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador", "Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador",
"No hay un contrato en vigor": "No hay un contrato en vigor", "No hay un contrato en vigor": "No hay un contrato en vigor",
"No se permite fichar a futuro": "No se permite fichar a futuro", "No se permite fichar a futuro": "No se permite fichar a futuro",
"No está permitido trabajar": "No está permitido trabajar", "No está permitido trabajar": "No está permitido trabajar",
"Fichadas impares": "Fichadas impares", "Fichadas impares": "Fichadas impares",
"Descanso diario 12h.": "Descanso diario 12h.", "Descanso diario 12h.": "Descanso diario 12h.",
"Descanso semanal 36h. / 72h.": "Descanso semanal 36h. / 72h.", "Descanso semanal 36h. / 72h.": "Descanso semanal 36h. / 72h.",
"Dirección incorrecta": "Dirección incorrecta", "Dirección incorrecta": "Dirección incorrecta",
"Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador", "Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador",
"Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador", "Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador",
"Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente", "Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente",
"This route does not exists": "Esta ruta no existe", "This route does not exists": "Esta ruta no existe",
"Claim pickup order sent": "Reclamación Orden de recogida enviada [{{claimId}}]({{{claimUrl}}}) al cliente *{{clientName}}*", "Claim pickup order sent": "Reclamación Orden de recogida enviada [{{claimId}}]({{{claimUrl}}}) al cliente *{{clientName}}*",
"You don't have grant privilege": "No tienes privilegios para dar privilegios", "You don't have grant privilege": "No tienes privilegios para dar privilegios",
"You don't own the role and you can't assign it to another user": "No eres el propietario del rol y no puedes asignarlo a otro usuario", "You don't own the role and you can't assign it to another user": "No eres el propietario del rol y no puedes asignarlo a otro usuario",
"Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) fusionado con [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})", "Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) fusionado con [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})",
"Already has this status": "Ya tiene este estado", "Already has this status": "Ya tiene este estado",
"There aren't records for this week": "No existen registros para esta semana", "There aren't records for this week": "No existen registros para esta semana",
"Empty data source": "Origen de datos vacio", "Empty data source": "Origen de datos vacio",
"App locked": "Aplicación bloqueada por el usuario {{userId}}", "App locked": "Aplicación bloqueada por el usuario {{userId}}",
"Email verify": "Correo de verificación", "Email verify": "Correo de verificación",
"Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment", "Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment",
"Receipt's bank was not found": "No se encontró el banco del recibo", "Receipt's bank was not found": "No se encontró el banco del recibo",
"This receipt was not compensated": "Este recibo no ha sido compensado", "This receipt was not compensated": "Este recibo no ha sido compensado",
"Client's email was not found": "No se encontró el email del cliente", "Client's email was not found": "No se encontró el email del cliente",
"Negative basis": "Base negativa", "Negative basis": "Base negativa",
"This worker code already exists": "Este codigo de trabajador ya existe", "This worker code already exists": "Este codigo de trabajador ya existe",
"This personal mail already exists": "Este correo personal ya existe", "This personal mail already exists": "Este correo personal ya existe",
"This worker already exists": "Este trabajador ya existe", "This worker already exists": "Este trabajador ya existe",
"App name does not exist": "El nombre de aplicación no es válido", "App name does not exist": "El nombre de aplicación no es válido",
"Try again": "Vuelve a intentarlo", "Try again": "Vuelve a intentarlo",
"Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9", "Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9",
"Failed to upload delivery note": "Error al subir albarán {{id}}", "Failed to upload delivery note": "Error al subir albarán {{id}}",
"The DOCUWARE PDF document does not exists": "El documento PDF Docuware no existe", "The DOCUWARE PDF document does not exists": "El documento PDF Docuware no existe",
"It is not possible to modify tracked sales": "No es posible modificar líneas de pedido que se hayan empezado a preparar", "It is not possible to modify tracked sales": "No es posible modificar líneas de pedido que se hayan empezado a preparar",
"It is not possible to modify sales that their articles are from Floramondo": "No es posible modificar líneas de pedido cuyos artículos sean de Floramondo", "It is not possible to modify sales that their articles are from Floramondo": "No es posible modificar líneas de pedido cuyos artículos sean de Floramondo",
"It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas", "It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas",
"A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.", "A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.",
"There is no assigned email for this client": "No hay correo asignado para este cliente", "There is no assigned email for this client": "No hay correo asignado para este cliente",
"Exists an invoice with a future date": "Existe una factura con fecha posterior", "Exists an invoice with a future date": "Existe una factura con fecha posterior",
"Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite", "Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite",
"Warehouse inventory not set": "El almacén inventario no está establecido", "Warehouse inventory not set": "El almacén inventario no está establecido",
"This locker has already been assigned": "Esta taquilla ya ha sido asignada", "This locker has already been assigned": "Esta taquilla ya ha sido asignada",
"Tickets with associated refunds": "No se pueden borrar tickets con abonos asociados. Este ticket está asociado al abono Nº %d", "Tickets with associated refunds": "No se pueden borrar tickets con abonos asociados. Este ticket está asociado al abono Nº %d",
"Not exist this branch": "La rama no existe", "Not exist this branch": "La rama no existe",
"This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado", "This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado",
"Collection does not exist": "La colección no existe", "Collection does not exist": "La colección no existe",
"Cannot obtain exclusive lock": "No se puede obtener un bloqueo exclusivo", "Cannot obtain exclusive lock": "No se puede obtener un bloqueo exclusivo",
"Insert a date range": "Inserte un rango de fechas", "Insert a date range": "Inserte un rango de fechas",
"Added observation": "{{user}} añadió esta observacion: {{text}}", "Added observation": "{{user}} añadió esta observacion: {{text}}",
"Comment added to client": "Observación añadida al cliente {{clientFk}}", "Comment added to client": "Observación añadida al cliente {{clientFk}}",
"Invalid auth code": "Código de verificación incorrecto", "Invalid auth code": "Código de verificación incorrecto",
"Invalid or expired verification code": "Código de verificación incorrecto o expirado", "Invalid or expired verification code": "Código de verificación incorrecto o expirado",
"Cannot create a new claimBeginning from a different ticket": "No se puede crear una línea de reclamación de un ticket diferente al origen", "Cannot create a new claimBeginning from a different ticket": "No se puede crear una línea de reclamación de un ticket diferente al origen",
"company": "Compañía", "company": "Compañía",
"country": "País", "country": "País",
"clientId": "Id cliente", "clientId": "Id cliente",
"clientSocialName": "Cliente", "clientSocialName": "Cliente",
"amount": "Importe", "amount": "Importe",
"taxableBase": "Base", "taxableBase": "Base",
"ticketFk": "Id ticket", "ticketFk": "Id ticket",
"isActive": "Activo", "isActive": "Activo",
"hasToInvoice": "Facturar", "hasToInvoice": "Facturar",
"isTaxDataChecked": "Datos comprobados", "isTaxDataChecked": "Datos comprobados",
"comercialId": "Id comercial", "comercialId": "Id comercial",
"comercialName": "Comercial", "comercialName": "Comercial",
"Pass expired": "La contraseña ha caducado, cambiela desde Salix", "Pass expired": "La contraseña ha caducado, cambiela desde Salix",
"Invalid NIF for VIES": "Invalid NIF for VIES", "Invalid NIF for VIES": "Invalid NIF for VIES",
"Ticket does not exist": "Este ticket no existe", "Ticket does not exist": "Este ticket no existe",
"Ticket is already signed": "Este ticket ya ha sido firmado", "Ticket is already signed": "Este ticket ya ha sido firmado",
"Authentication failed": "Autenticación fallida", "Authentication failed": "Autenticación fallida",
"You can't use the same password": "No puedes usar la misma contraseña", "You can't use the same password": "No puedes usar la misma contraseña",
"You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono", "You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono",
"Fecha fuera de rango": "Fecha fuera de rango", "Fecha fuera de rango": "Fecha fuera de rango",
"Error while generating PDF": "Error al generar PDF", "Error while generating PDF": "Error al generar PDF",
"Error when sending mail to client": "Error al enviar el correo al cliente", "Error when sending mail to client": "Error al enviar el correo al cliente",
"Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico", "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico",
"The renew period has not been exceeded": "El periodo de renovación no ha sido superado", "The renew period has not been exceeded": "El periodo de renovación no ha sido superado",
"Valid priorities": "Prioridades válidas: %d", "Valid priorities": "Prioridades válidas: %d",
"hasAnyNegativeBase": "Base negativa para los tickets: {{ticketsIds}}", "hasAnyNegativeBase": "Base negativa para los tickets: {{ticketsIds}}",
"hasAnyPositiveBase": "Base positivas para los tickets: {{ticketsIds}}", "hasAnyPositiveBase": "Base positivas para los tickets: {{ticketsIds}}",
"You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado", "You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado",
"This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s", "This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s",
"The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias", "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias",
"You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado", "You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado",
"This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado", "This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado",
"You don't have enough privileges.": "No tienes suficientes permisos.", "You don't have enough privileges.": "No tienes suficientes permisos.",
"This ticket is locked": "Este ticket está bloqueado.", "This ticket is locked": "Este ticket está bloqueado.",
"This ticket is not editable.": "Este ticket no es editable.", "This ticket is not editable.": "Este ticket no es editable.",
"The ticket doesn't exist.": "No existe el ticket.", "The ticket doesn't exist.": "No existe el ticket.",
"Social name should be uppercase": "La razón social debe ir en mayúscula", "Social name should be uppercase": "La razón social debe ir en mayúscula",
"Street should be uppercase": "La dirección fiscal debe ir en mayúscula", "Street should be uppercase": "La dirección fiscal debe ir en mayúscula",
"Ticket without Route": "Ticket sin ruta", "Ticket without Route": "Ticket sin ruta",
"Select a different client": "Seleccione un cliente distinto", "Select a different client": "Seleccione un cliente distinto",
"Fill all the fields": "Rellene todos los campos", "Fill all the fields": "Rellene todos los campos",
"The response is not a PDF": "La respuesta no es un PDF", "The response is not a PDF": "La respuesta no es un PDF",
"Booking completed": "Reserva completada", "Booking completed": "Reserva completada",
"The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación",
"The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada", "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada",
"User disabled": "Usuario desactivado", "User disabled": "Usuario desactivado",
"The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima",
"quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima",
"Cannot past travels with entries": "No se pueden pasar envíos con entradas", "Cannot past travels with entries": "No se pueden pasar envíos con entradas",
"It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}",
"This claim has been updated": "La reclamación con Id: {{claimId}}, ha sido actualizada", "This claim has been updated": "La reclamación con Id: {{claimId}}, ha sido actualizada",
"This user does not have an assigned tablet": "Este usuario no tiene tablet asignada", "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada",
"Field are invalid": "El campo '{{tag}}' no es válido", "Field are invalid": "El campo '{{tag}}' no es válido",
"Incorrect pin": "Pin incorrecto.", "Incorrect pin": "Pin incorrecto.",
"You already have the mailAlias": "Ya tienes este alias de correo", "You already have the mailAlias": "Ya tienes este alias de correo",
"The alias cant be modified": "Este alias de correo no puede ser modificado", "The alias cant be modified": "Este alias de correo no puede ser modificado",
"No tickets to invoice": "No hay tickets para facturar", "No tickets to invoice": "No hay tickets para facturar",
"this warehouse has not dms": "El Almacén no acepta documentos", "this warehouse has not dms": "El Almacén no acepta documentos",
"This ticket already has a cmr saved": "Este ticket ya tiene un cmr guardado", "This ticket already has a cmr saved": "Este ticket ya tiene un cmr guardado",
"Name should be uppercase": "El nombre debe ir en mayúscula", "Name should be uppercase": "El nombre debe ir en mayúscula",
"Bank entity must be specified": "La entidad bancaria es obligatoria", "Bank entity must be specified": "La entidad bancaria es obligatoria",
"An email is necessary": "Es necesario un email", "An email is necessary": "Es necesario un email",
"You cannot update these fields": "No puedes actualizar estos campos", "You cannot update these fields": "No puedes actualizar estos campos",
"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",
"The line could not be marked": "La linea no puede ser marcada" "The line could not be marked": "La linea no puede ser marcada",
} "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

@ -34,7 +34,8 @@ module.exports = Self => {
http: { http: {
path: '/:id/claim-pickup-pdf', path: '/:id/claim-pickup-pdf',
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.claimPickupPdf = (ctx, id) => Self.printReport(ctx, id, 'claim-pickup-order'); Self.claimPickupPdf = (ctx, id) => Self.printReport(ctx, id, 'claim-pickup-order');

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

@ -45,7 +45,8 @@ module.exports = Self => {
http: { http: {
path: '/:id/campaign-metrics-pdf', path: '/:id/campaign-metrics-pdf',
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.campaignMetricsPdf = (ctx, id) => Self.printReport(ctx, id, 'campaign-metrics'); Self.campaignMetricsPdf = (ctx, id) => Self.printReport(ctx, id, 'campaign-metrics');

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

@ -33,7 +33,8 @@ module.exports = Self => {
http: { http: {
path: '/:id/entry-order-pdf', path: '/:id/entry-order-pdf',
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.entryOrderPdf = (ctx, id) => Self.printReport(ctx, id, 'entry-order'); Self.entryOrderPdf = (ctx, id) => Self.printReport(ctx, id, 'entry-order');

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

@ -34,7 +34,8 @@ module.exports = Self => {
http: { http: {
path: '/:reference/exportation-pdf', path: '/:reference/exportation-pdf',
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.exportationPdf = (ctx, reference) => Self.printReport(ctx, reference, 'exportation'); Self.exportationPdf = (ctx, reference) => Self.printReport(ctx, reference, 'exportation');

View File

@ -37,23 +37,24 @@ module.exports = Self => {
http: { http: {
path: '/:reference/invoice-csv', path: '/:reference/invoice-csv',
verb: 'GET' verb: 'GET'
} },
accessScopes: ['read:multimedia']
}); });
Self.invoiceCsv = async reference => { Self.invoiceCsv = async reference => {
const sales = await Self.rawSql(` const sales = await Self.rawSql(`
SELECT io.ref Invoice, SELECT io.ref Invoice,
io.issued InvoiceDate, io.issued InvoiceDate,
s.ticketFk Ticket, s.ticketFk Ticket,
s.itemFk Item, s.itemFk Item,
s.concept Description, s.concept Description,
i.size, i.size,
i.subName Producer, i.subName Producer,
s.quantity Quantity, s.quantity Quantity,
s.price Price, s.price Price,
s.discount Discount, s.discount Discount,
s.created Created, s.created Created,
tc.code Taxcode, tc.code Taxcode,
tc.description TaxDescription, tc.description TaxDescription,
i.tag5, i.tag5,
i.value5, i.value5,
@ -67,14 +68,14 @@ module.exports = Self => {
i.value9, i.value9,
i.tag10, i.tag10,
i.value10 i.value10
FROM sale s FROM sale s
JOIN ticket t ON t.id = s.ticketFk JOIN ticket t ON t.id = s.ticketFk
JOIN item i ON i.id = s.itemFk JOIN item i ON i.id = s.itemFk
JOIN supplier s2 ON s2.id = t.companyFk JOIN supplier s2 ON s2.id = t.companyFk
JOIN itemTaxCountry itc ON itc.itemFk = i.id JOIN itemTaxCountry itc ON itc.itemFk = i.id
AND itc.countryFk = s2.countryFk AND itc.countryFk = s2.countryFk
JOIN taxClass tc ON tc.id = itc.taxClassFk JOIN taxClass tc ON tc.id = itc.taxClassFk
JOIN invoiceOut io ON io.ref = t.refFk JOIN invoiceOut io ON io.ref = t.refFk
WHERE t.refFk = ? WHERE t.refFk = ?
ORDER BY s.ticketFk, s.created`, [reference]); ORDER BY s.ticketFk, s.created`, [reference]);

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