Merge branch '2049-hotfix_percentage' of verdnatura/salix into master
gitea/salix/master This commit looks good Details
gitea/salix/test This commit looks good Details
gitea/salix/dev This commit looks good Details

This commit is contained in:
Joan Sanchez 2020-01-29 10:29:35 +00:00 committed by Gitea
commit a078898627
394 changed files with 17057 additions and 16974 deletions

View File

@ -2,8 +2,6 @@
{ {
// Carácter predeterminado de final de línea. // Carácter predeterminado de final de línea.
"files.eol": "\n", "files.eol": "\n",
"vsicons.presets.angular": false,
"eslint.autoFixOnSave": true,
"editor.codeActionsOnSave": { "editor.codeActionsOnSave": {
"source.fixAll.eslint": true "source.fixAll.eslint": true
} }

138
back/methods/chat/send.js Normal file
View File

@ -0,0 +1,138 @@
const request = require('request-promise-native');
module.exports = Self => {
Self.remoteMethodCtx('send', {
description: 'Send a RocketChat message',
accessType: 'WRITE',
accepts: [{
arg: 'to',
type: 'String',
required: true,
description: 'User (@) or channel (#) to send the message'
}, {
arg: 'message',
type: 'String',
required: true,
description: 'The message'
}],
returns: {
type: 'Object',
root: true
},
http: {
path: `/send`,
verb: 'POST'
}
});
Self.send = async(ctx, to, message) => {
const models = Self.app.models;
const accessToken = ctx.req.accessToken;
const sender = await models.Account.findById(accessToken.userId);
const recipient = to.replace('@', '');
if (sender.name != recipient)
return sendMessage(sender, to, `@${sender.name}: ${message} `);
};
async function sendMessage(sender, channel, message) {
const config = await getConfig();
const avatar = `${config.host}/avatar/${sender.name}`;
const uri = `${config.api}/chat.postMessage`;
return sendAuth(uri, {
'channel': channel,
'avatar': avatar,
'text': message
}).catch(async error => {
if (error.statusCode === 401 && !this.resendAttempted) {
this.resendAttempted = true;
return sendMessage(sender, channel, message);
}
throw new Error(error.message);
});
}
/**
* Returns a rocketchat token
* @return {Object} userId and authToken
*/
async function getAuthToken() {
if (!this.auth || this.auth && !this.auth.authToken) {
const config = await getConfig();
const uri = `${config.api}/login`;
const res = await send(uri, {
user: config.user,
password: config.password
});
this.auth = res.data;
}
return this.auth;
}
/**
* Returns a rocketchat config
* @return {Object} Auth config
*/
async function getConfig() {
if (!this.chatConfig) {
const models = Self.app.models;
this.chatConfig = await models.ChatConfig.findOne();
}
return this.chatConfig;
}
/**
* Send unauthenticated request
* @param {*} uri - Request uri
* @param {*} body - Request params
* @param {*} options - Request options
*
* @return {Object} Request response
*/
async function send(uri, body, options) {
if (process.env.NODE_ENV !== 'production') {
return new Promise(resolve => {
return resolve({statusCode: 200, message: 'Fake notification sent'});
});
}
const defaultOptions = {
method: 'POST',
uri: uri,
body: body,
headers: {'content-type': 'application/json'},
json: true
};
if (options) Object.assign(defaultOptions, options);
return request(defaultOptions);
}
/**
* Send authenticated request
* @param {*} uri - Request uri
* @param {*} body - Request params
*
* @return {Object} Request response
*/
async function sendAuth(uri, body) {
const login = await getAuthToken();
const options = {
headers: {'content-type': 'application/json'}
};
if (login) {
options.headers['X-Auth-Token'] = login.authToken;
options.headers['X-User-Id'] = login.userId;
}
return send(uri, body, options);
}
};

View File

@ -0,0 +1,53 @@
module.exports = Self => {
Self.remoteMethodCtx('sendCheckingPresence', {
description: 'Sends a RocketChat message to a working worker or department channel',
accessType: 'WRITE',
accepts: [{
arg: 'workerId',
type: 'Number',
required: true,
description: 'The worker id of the destinatary'
}, {
arg: 'message',
type: 'String',
required: true,
description: 'The message'
}],
returns: {
type: 'Object',
root: true
},
http: {
path: `/sendCheckingPresence`,
verb: 'POST'
}
});
Self.sendCheckingPresence = async(ctx, workerId, message) => {
const models = Self.app.models;
const account = await models.Account.findById(workerId);
const query = `SELECT worker_isWorking(?) isWorking`;
const [result] = await Self.rawSql(query, [workerId]);
let room;
if (result.isWorking)
room = `@${account.name}`;
else {
const workerDepartment = await models.WorkerDepartment.findById(workerId, {
include: {
relation: 'department'
}
});
const department = workerDepartment.department();
const channelName = department.chatName;
room = `#${channelName}`;
if (channelName)
room = `#${channelName}`;
else room = `@${account.name}`;
}
return Self.send(ctx, room, message);
};
};

View File

@ -1,4 +1,3 @@
const request = require('request-promise-native');
module.exports = Self => { module.exports = Self => {
Self.remoteMethodCtx('sendMessage', { Self.remoteMethodCtx('sendMessage', {
description: 'Send a RocketChat message', description: 'Send a RocketChat message',
@ -24,73 +23,8 @@ module.exports = Self => {
} }
}); });
// FIXME: Deprecate this method #2019
Self.sendMessage = async(ctx, to, message) => { Self.sendMessage = async(ctx, to, message) => {
const models = Self.app.models; return Self.send(ctx, to, message);
const accessToken = ctx.req.accessToken;
const sender = await models.Account.findById(accessToken.userId);
const recipient = to.replace('@', '');
if (sender.name != recipient)
return sendMessage(to, `@${sender.name}: ${message}`);
}; };
async function sendMessage(name, message) {
const models = Self.app.models;
const chatConfig = await models.ChatConfig.findOne();
if (!Self.token)
Self.token = await login();
const uri = `${chatConfig.uri}/chat.postMessage`;
return send(uri, {
'channel': name,
'text': message
}).catch(async error => {
if (error.statusCode === 401 && !Self.loginAttempted) {
Self.token = await login();
Self.loginAttempted = true;
return sendMessage(name, message);
}
throw new Error(error.message);
});
}
/**
* Returns a rocketchat token
* @return {Object} userId and authToken
*/
async function login() {
const models = Self.app.models;
const chatConfig = await models.ChatConfig.findOne();
const uri = `${chatConfig.uri}/login`;
return send(uri, {
user: chatConfig.user,
password: chatConfig.password
}).then(res => res.data);
}
function send(uri, body) {
if (process.env.NODE_ENV !== 'production') {
return new Promise(resolve => {
return resolve({statusCode: 200, message: 'Fake notification sent'});
});
}
const options = {
method: 'POST',
uri: uri,
body: body,
headers: {'content-type': 'application/json'},
json: true
};
if (Self.token) {
options.headers['X-Auth-Token'] = Self.token.authToken;
options.headers['X-User-Id'] = Self.token.userId;
}
return request(options);
}
}; };

View File

@ -1,9 +1,9 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
describe('chat sendMessage()', () => { describe('chat send()', () => {
it('should return a "Fake notification sent" as response', async() => { it('should return a "Fake notification sent" as response', async() => {
let ctx = {req: {accessToken: {userId: 1}}}; let ctx = {req: {accessToken: {userId: 1}}};
let response = await app.models.Chat.sendMessage(ctx, '@salesPerson', 'I changed something'); let response = await app.models.Chat.send(ctx, '@salesPerson', 'I changed something');
expect(response.statusCode).toEqual(200); expect(response.statusCode).toEqual(200);
expect(response.message).toEqual('Fake notification sent'); expect(response.message).toEqual('Fake notification sent');
@ -11,7 +11,7 @@ describe('chat sendMessage()', () => {
it('should not return a response', async() => { it('should not return a response', async() => {
let ctx = {req: {accessToken: {userId: 18}}}; let ctx = {req: {accessToken: {userId: 18}}};
let response = await app.models.Chat.sendMessage(ctx, '@salesPerson', 'I changed something'); let response = await app.models.Chat.send(ctx, '@salesPerson', 'I changed something');
expect(response).toBeUndefined(); expect(response).toBeUndefined();
}); });

View File

@ -0,0 +1,65 @@
const app = require('vn-loopback/server/server');
describe('chat sendCheckingPresence()', () => {
const departmentId = 23;
const workerId = 107;
let timeEntry;
afterAll(async done => {
const department = await app.models.Department.findById(departmentId);
await department.updateAttribute('chatName', null);
await app.models.WorkerTimeControl.destroyById(timeEntry.id);
done();
});
it(`should call to send() method with the worker username when no department channel is specified
and then return a "Fake notification sent" as response`, async() => {
const ctx = {req: {accessToken: {userId: 1}}};
const chatModel = app.models.Chat;
spyOn(chatModel, 'send').and.callThrough();
const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something');
expect(response.statusCode).toEqual(200);
expect(response.message).toEqual('Fake notification sent');
expect(chatModel.send).toHaveBeenCalledWith(ctx, '@HankPym', 'I changed something');
});
it(`should call to send() method with the worker department channel if is specified
and then return a "Fake notification sent" as response`, async() => {
const ctx = {req: {accessToken: {userId: 1}}};
const chatModel = app.models.Chat;
spyOn(chatModel, 'send').and.callThrough();
const department = await app.models.Department.findById(departmentId);
await department.updateAttribute('chatName', 'cooler');
const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something');
expect(response.statusCode).toEqual(200);
expect(response.message).toEqual('Fake notification sent');
expect(chatModel.send).toHaveBeenCalledWith(ctx, '#cooler', 'I changed something');
});
it(`should call to send() method with the worker username when the worker is working`, async() => {
const ctx = {req: {accessToken: {userId: 1}}};
const chatModel = app.models.Chat;
spyOn(chatModel, 'send').and.callThrough();
const today = new Date();
today.setHours(6, 0);
timeEntry = await app.models.WorkerTimeControl.create({
userFk: workerId,
timed: today,
manual: false,
direction: 'in'
});
const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something');
expect(response.statusCode).toEqual(200);
expect(response.message).toEqual('Fake notification sent');
expect(chatModel.send).toHaveBeenCalledWith(ctx, '@HankPym', 'I changed something');
});
});

View File

@ -22,8 +22,10 @@ module.exports = Self => {
Self.removeFile = async(ctx, id) => { Self.removeFile = async(ctx, id) => {
const models = Self.app.models; const models = Self.app.models;
const trashDmsType = await models.DmsType.findOne({where: {code: 'trash'}});
const dms = await models.Dms.findById(id); const dms = await models.Dms.findById(id);
const trashDmsType = await models.DmsType.findOne({
where: {code: 'trash'}
});
const hasWriteRole = await models.DmsType.hasWriteRole(ctx, dms.dmsTypeFk); const hasWriteRole = await models.DmsType.hasWriteRole(ctx, dms.dmsTypeFk);
if (!hasWriteRole) if (!hasWriteRole)

View File

@ -2,6 +2,7 @@ const app = require('vn-loopback/server/server');
describe('dms downloadFile()', () => { describe('dms downloadFile()', () => {
let dmsId = 1; let dmsId = 1;
it('should return a response for an employee with text content-type', async() => { it('should return a response for an employee with text content-type', async() => {
let workerId = 107; let workerId = 107;
let ctx = {req: {accessToken: {userId: workerId}}}; let ctx = {req: {accessToken: {userId: workerId}}};

View File

@ -1,48 +0,0 @@
module.exports = Self => {
Self.remoteMethodCtx('send', {
description: 'Send message to user',
accessType: 'WRITE',
accepts: [{
arg: 'data',
type: 'object',
required: true,
description: 'recipientFk, message',
http: {source: 'body'}
}, {
arg: 'context',
type: 'object',
http: function(ctx) {
return ctx;
}
}],
returns: {
type: 'boolean',
root: true
},
http: {
path: `/:recipient/send`,
verb: 'post'
}
});
Self.send = async(ctx, data, options) => {
const accessToken = ctx.options && ctx.options.accessToken || ctx.req && ctx.req.accessToken;
const userId = accessToken.userId;
const models = Self.app.models;
const sender = await models.Account.findById(userId, null, options);
const recipient = await models.Account.findById(data.recipientFk, null, options);
await Self.create({
sender: sender.name,
recipient: recipient.name,
message: data.message
}, options);
return await models.MessageInbox.create({
sender: sender.name,
recipient: recipient.name,
finalRecipient: recipient.name,
message: data.message
}, options);
};
};

View File

@ -1,14 +0,0 @@
const app = require('vn-loopback/server/server');
describe('message send()', () => {
it('should return a response containing the same message in params', async() => {
let ctx = {req: {accessToken: {userId: 1}}};
let params = {
recipientFk: 1,
message: 'I changed something'
};
let response = await app.models.Message.send(ctx, params, {transaction: 'You'});
expect(response.message).toEqual(params.message);
});
});

View File

@ -23,12 +23,6 @@
"Delivery": { "Delivery": {
"dataSource": "vn" "dataSource": "vn"
}, },
"Message": {
"dataSource": "vn"
},
"MessageInbox": {
"dataSource": "vn"
},
"Province": { "Province": {
"dataSource": "vn" "dataSource": "vn"
}, },
@ -59,12 +53,6 @@
"Postcode": { "Postcode": {
"dataSource": "vn" "dataSource": "vn"
}, },
"UserPhoneType": {
"dataSource": "vn"
},
"UserPhone": {
"dataSource": "vn"
},
"UserLog": { "UserLog": {
"dataSource": "vn" "dataSource": "vn"
} }

View File

@ -13,7 +13,10 @@
"type": "Number", "type": "Number",
"description": "Identifier" "description": "Identifier"
}, },
"uri": { "host": {
"type": "String"
},
"api": {
"type": "String" "type": "String"
}, },
"user": { "user": {

View File

@ -1,3 +1,5 @@
module.exports = Self => { module.exports = Self => {
require('../methods/chat/send')(Self);
require('../methods/chat/sendMessage')(Self); require('../methods/chat/sendMessage')(Self);
require('../methods/chat/sendCheckingPresence')(Self);
}; };

View File

@ -3,6 +3,9 @@
"name": "Dms", "name": "Dms",
"description": "Documental Managment system", "description": "Documental Managment system",
"base": "VnModel", "base": "VnModel",
"log": {
"showField": "reference"
},
"options": { "options": {
"mysql": { "mysql": {
"table": "dms" "table": "dms"

View File

@ -1,43 +0,0 @@
{
"name": "MessageInbox",
"base": "VnModel",
"options": {
"mysql": {
"table": "messageInbox"
}
},
"properties": {
"id": {
"type": "Number",
"id": true,
"description": "Identifier"
},
"sender": {
"type": "String",
"required": true
},
"recipient": {
"type": "String",
"required": true
},
"finalRecipient": {
"type": "String",
"required": true
},
"message": {
"type": "String"
}
},
"relations": {
"remitter": {
"type": "belongsTo",
"model": "User",
"foreignKey": "sender"
},
"receptor": {
"type": "belongsTo",
"model": "User",
"foreignKey": "recipient"
}
}
}

View File

@ -1,3 +0,0 @@
module.exports = Self => {
require('../methods/message/send')(Self);
};

View File

@ -1,39 +0,0 @@
{
"name": "Message",
"base": "VnModel",
"options": {
"mysql": {
"table": "message"
}
},
"properties": {
"id": {
"type": "Number",
"id": true,
"description": "Identifier"
},
"sender": {
"type": "String",
"required": true
},
"recipient": {
"type": "String",
"required": true
},
"message": {
"type": "String"
}
},
"relations": {
"remitter": {
"type": "belongsTo",
"model": "User",
"foreignKey": "sender"
},
"receptor": {
"type": "belongsTo",
"model": "User",
"foreignKey": "recipient"
}
}
}

View File

@ -1,18 +0,0 @@
{
"name": "UserPhoneType",
"base": "VnModel",
"options": {
"mysql": {
"table": "userPhoneType"
}
},
"properties": {
"code": {
"id": true,
"type": "String"
},
"description": {
"type": "String"
}
}
}

View File

@ -1,9 +0,0 @@
let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.rewriteDbError(function(err) {
if (err.code === 'ER_DUP_ENTRY')
return new UserError(`This phone already exists`);
return err;
});
};

View File

@ -1,39 +0,0 @@
{
"name": "UserPhone",
"base": "Loggable",
"log": {
"model":"UserLog",
"relation": "user"
},
"options": {
"mysql": {
"table": "userPhone"
}
},
"properties": {
"id": {
"id": true,
"type": "Number"
},
"phone": {
"type": "Number",
"required": true
},
"typeFk": {
"type": "String",
"required": true
}
},
"relations": {
"user": {
"type": "belongsTo",
"model": "Account",
"foreignKey": "userFk"
},
"type": {
"type": "belongsTo",
"model": "UserPhoneType",
"foreignKey": "typeFk"
}
}
}

View File

@ -1,117 +0,0 @@
DROP procedure IF EXISTS `vn`.`catalog_calculate`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`catalog_calculate`(
vLanded DATE,
vAddressFk INT,
vAgencyModeFk INT)
proc: BEGIN
/**
* Calcula los articulos disponibles y sus precios
*
* @table tmp.item(itemFk) Listado de artículos a calcular
* @param vLanded Fecha de recepcion de mercancia
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id de la agencia
* @return tmp.ticketCalculateItem(itemFk, available, producer,
* item, size, stems, category, inkFk, image, origin, price)
* @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk)
* @return tmp.ticketComponent
* @return tmp.ticketComponentPrice
* @return tmp.zoneGetShipped
**/
DECLARE vAvailableCalc INT;
DECLARE vShipped DATE;
DECLARE vClient INT;
DECLARE vWarehouseFk SMALLINT;
DECLARE vZoneFk INT;
DECLARE vDone BOOL;
DECLARE cTravelTree CURSOR FOR
SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-- Establece los almacenes y las fechas que van a entrar al disponible
SELECT clientFk INTO vClient
FROM address WHERE id = vAddressFk;
CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot(
`warehouseFk` smallint(5) unsigned NOT NULL,
`itemFk` int(11) NOT NULL,
`available` double DEFAULT NULL,
`buyFk` int(11) DEFAULT NULL,
`fix` tinyint(3) unsigned DEFAULT '0',
KEY `itemFk` (`itemFk`),
KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
OPEN cTravelTree;
l: LOOP
SET vDone = FALSE;
FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped;
IF vDone THEN
LEAVE l;
END IF;
CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped);
CALL buyUltimate (vWarehouseFk, vShipped);
INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk)
SELECT vWarehouseFk,
i.item_id,
IFNULL(i.available, 0),
bu.buyFk
FROM `cache`.available i
JOIN tmp.item br ON br.itemFk = i.item_id
LEFT JOIN item it ON it.id = i.item_id
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id
WHERE i.calc_id = vAvailableCalc
AND it.id != 100
AND i.available > 0;
DROP TEMPORARY TABLE tmp.buyUltimate;
END LOOP;
CLOSE cTravelTree;
CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem;
CREATE TEMPORARY TABLE tmp.ticketCalculateItem
ENGINE = MEMORY
SELECT
b.itemFk,
SUM(b.available) available,
p.name producer,
i.name item,
i.size size,
i.stems,
i.category,
i.inkFk,
i.image,
o.code origin,
bl.price,
bl.priceKg
FROM tmp.ticketLot b
JOIN item i ON b.itemFk = i.id
LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible
JOIN origin o ON o.id = i.originFk
JOIN (
SELECT MIN(price) price, itemFk, priceKg
FROM tmp.ticketComponentPrice
GROUP BY itemFk
) bl ON bl.itemFk = b.itemFk
GROUP BY b.itemFk;
END$$
DELIMITER ;

View File

@ -1,27 +0,0 @@
DROP FUNCTION IF EXISTS `vn`.`address_getGeo`;
DELIMITER $$
CREATE DEFINER=`root`@`%` FUNCTION `vn`.`address_getGeo` (vSelf INT)
RETURNS INT
DETERMINISTIC
BEGIN
/**
* Returns the geo for the passed address.
*
* @param vSelf The address id
* @return The geo id
*/
DECLARE vGeoFk INT;
SELECT p.geoFk INTO vGeoFk
FROM address a
JOIN town t ON t.provinceFk = a.provinceFk
JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode
WHERE a.id = vSelf
ORDER BY (a.city SOUNDS LIKE t.`name`) DESC
LIMIT 1;
RETURN vGeoFk;
END$$
DELIMITER ;

View File

@ -1,56 +0,0 @@
USE `vn`;
CREATE TABLE `vn`.`zoneWarehouse` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`zoneFk` int(11) NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`),
KEY `warehouseFk` (`warehouseFk`),
CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE/*,
CONSTRAINT `zoneWarehouse_ibfk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE*/
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
CREATE TABLE `vn`.`zoneEvent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zoneFk` int(11) NOT NULL,
`from` date DEFAULT NULL,
`to` date DEFAULT NULL,
`weekDays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL,
`hour` datetime DEFAULT NULL,
`travelingDays` int(11) DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
`bonus` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `zoneFk` (`zoneFk`),
CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;
ALTER TABLE `vn`.`zoneEvent`
ADD COLUMN `type` ENUM('day', 'indefinitely', 'range') NOT NULL AFTER `zoneFk`,
ADD COLUMN `dated` DATE NULL DEFAULT NULL AFTER `type`,
CHANGE COLUMN `from` `started` DATE NULL DEFAULT NULL ,
CHANGE COLUMN `to` `ended` DATE NULL DEFAULT NULL ;
CREATE TABLE `vn`.`zoneExclusion` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zoneFk` int(11) NOT NULL,
`day` date NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zoneFk_2` (`zoneFk`,`day`),
KEY `zoneFk` (`zoneFk`),
CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
ALTER TABLE `vn`.`zone`
DROP FOREIGN KEY `fk_zone_1`;
ALTER TABLE `vn`.`zone`
CHANGE COLUMN `warehouseFk` `warehouseFk` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ;
ALTER TABLE `vn`.`zone`
ADD CONSTRAINT `fk_zone_1`
FOREIGN KEY (`warehouseFk`)
REFERENCES `vn`.`warehouse` (`id`)
ON DELETE NO ACTION
ON UPDATE CASCADE;
ALTER TABLE `vn`.`zoneExclusion`
CHANGE COLUMN `day` `dated` DATE NOT NULL ;

View File

@ -1,16 +0,0 @@
DROP PROCEDURE IF EXISTS `vn`.`zone_getAvailable`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getAvailable`(vAddress INT, vLanded DATE)
BEGIN
CALL zone_getFromGeo(address_getGeo(vAddress));
CALL zone_getOptionsForLanding(vLanded);
SELECT * FROM tmp.zoneOption;
DROP TEMPORARY TABLE
tmp.zone,
tmp.zoneOption;
END$$
DELIMITER ;

View File

@ -1,52 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zone_getEvents`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`(
vProvinceFk INT,
vPostCode VARCHAR(255),
vAgencyModeFk INT)
BEGIN
/**
* Returns available events for the passed province/postcode and agency.
*
* @param vAgencyModeFk The agency mode id
* @param vProvinceFk The province id
* @param vPostCode The postcode or %NULL to use the province
*/
DECLARE vGeoFk INT;
IF vPostCode IS NOT NULL THEN
SELECT p.geoFk INTO vGeoFk
FROM postCode p
JOIN town t ON t.id = p.townFk
WHERE p.`code` = vPostCode
AND t.provinceFk = vProvinceFk;
ELSE
SELECT geoFk INTO vGeoFk
FROM province
WHERE id = vProvinceFk;
END IF;
CALL zone_getFromGeo(vGeoFk);
IF vAgencyModeFk IS NOT NULL THEN
DELETE t FROM tmp.zone t
JOIN zone z ON z.id = t.id
WHERE z.agencyModeFk != vAgencyModeFk;
END IF;
SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays
FROM tmp.zone t
JOIN zoneEvent e ON e.zoneFk = t.id;
SELECT e.zoneFk, e.dated
FROM tmp.zone t
JOIN zoneExclusion e ON e.zoneFk = t.id;
DROP TEMPORARY TABLE tmp.zone;
END$$
DELIMITER ;

View File

@ -1,58 +0,0 @@
DROP PROCEDURE IF EXISTS `vn`.`zone_getFromGeo`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getFromGeo`(vGeoFk INT)
BEGIN
/**
* Returns all zones which have the passed geo included.
*
* @param vGeoFk The geo id
* @return tmp.zone(id) The list of zones
*/
DECLARE vChildFk INT DEFAULT vGeoFk;
DECLARE vParentFk INT;
DECLARE vLevel INT DEFAULT 1;
DROP TEMPORARY TABLE IF EXISTS tNodes;
CREATE TEMPORARY TABLE tNodes
(PRIMARY KEY (id))
ENGINE = MEMORY
SELECT vGeoFk id, vLevel `level`;
myLoop: LOOP
SELECT parentFk INTO vParentFk
FROM zoneGeo
WHERE id = vChildFk;
SET vChildFk = vParentFk;
SET vLevel = vLevel + 1;
INSERT IGNORE INTO tNodes
SELECT vChildFk, vLevel
FROM DUAL
WHERE vChildFk IS NOT NULL;
IF ROW_COUNT() = 0 THEN
LEAVE myLoop;
END IF;
END LOOP;
DROP TEMPORARY TABLE IF EXISTS tmp.zone;
CREATE TEMPORARY TABLE tmp.zone
(INDEX (id))
ENGINE = MEMORY
SELECT id FROM (
SELECT zoneFk id, isIncluded
FROM (
SELECT i.zoneFk, i.isIncluded
FROM tNodes n
JOIN zoneIncluded i ON i.geoFk = n.id
ORDER BY zoneFk, n.`level`
) t
GROUP BY id HAVING isIncluded
) t;
DROP TEMPORARY TABLE tNodes;
END$$
DELIMITER ;

View File

@ -1,88 +0,0 @@
DROP procedure IF EXISTS `vn`.`zone_getLeaves`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getLeaves`(
vSelf INT,
vParentFk INT,
vSearch VARCHAR(255)
)
BEGIN
DECLARE vIsNumber BOOL;
DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != '';
DROP TEMPORARY TABLE IF EXISTS tNodes;
CREATE TEMPORARY TABLE tNodes
(UNIQUE (id))
ENGINE = MEMORY
SELECT id FROM zoneGeo LIMIT 0;
IF vIsSearch THEN
SET vIsNumber = vSearch REGEXP '^[0-9]+$';
INSERT INTO tNodes
SELECT id FROM zoneGeo
WHERE (vIsNumber AND `name` = vSearch)
OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%'))
LIMIT 1000;
ELSEIF vParentFk IS NULL THEN
INSERT INTO tNodes
SELECT geoFk FROM zoneIncluded
WHERE zoneFk = vSelf;
END IF;
IF vParentFk IS NULL THEN
DROP TEMPORARY TABLE IF EXISTS tChilds;
CREATE TEMPORARY TABLE tChilds
ENGINE = MEMORY
SELECT id FROM tNodes;
DROP TEMPORARY TABLE IF EXISTS tParents;
CREATE TEMPORARY TABLE tParents
ENGINE = MEMORY
SELECT id FROM zoneGeo LIMIT 0;
myLoop: LOOP
DELETE FROM tParents;
INSERT INTO tParents
SELECT parentFk id
FROM zoneGeo g
JOIN tChilds c ON c.id = g.id
WHERE g.parentFk IS NOT NULL;
INSERT IGNORE INTO tNodes
SELECT id FROM tParents;
IF ROW_COUNT() = 0 THEN
LEAVE myLoop;
END IF;
DELETE FROM tChilds;
INSERT INTO tChilds
SELECT id FROM tParents;
END LOOP;
DROP TEMPORARY TABLE
tChilds,
tParents;
END IF;
IF !vIsSearch THEN
INSERT IGNORE INTO tNodes
SELECT id FROM zoneGeo
WHERE parentFk <=> vParentFk;
END IF;
SELECT g.id,
g.`name`,
g.parentFk,
g.sons,
isIncluded selected
FROM zoneGeo g
JOIN tNodes n ON n.id = g.id
LEFT JOIN zoneIncluded i
ON i.geoFk = g.id AND i.zoneFk = vSelf
ORDER BY depth, selected DESC, `name`;
DROP TEMPORARY TABLE tNodes;
END$$
DELIMITER ;

View File

@ -1,42 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zone_getAgency`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAgency`(vAddress INT, vLanded DATE)
BEGIN
/**
* Devuelve el listado de agencias disponibles para la fecha
* y dirección pasadas.
*
* @param vAddress Id de dirección de envío, %NULL si es recogida
* @param vLanded Fecha de recogida
* @select Listado de agencias disponibles
*/
CALL zone_getFromGeo(address_getGeo(vAddress));
CALL zone_getOptionsForLanding(vLanded);
DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency;
CREATE TEMPORARY TABLE tmp.zoneGetAgency
(INDEX (agencyModeFk)) ENGINE = MEMORY
SELECT am.name agencyMode,
am.description,
z.agencyModeFk,
am.deliveryMethodFk,
TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped,
TRUE isIncluded,
zo.zoneFk
FROM tmp.zoneOption zo
JOIN zone z ON z.id = zo.zoneFk
JOIN agencyMode am ON am.id = z.agencyModeFk
GROUP BY agencyModeFk;
DROP TEMPORARY TABLE
tmp.zone,
tmp.zoneOption;
END$$
DELIMITER ;

View File

@ -1,2 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zone_getFirstShipped`;

View File

@ -1,40 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zone_getLanded`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT)
BEGIN
/**
* Devuelve una tabla temporal con el dia de recepcion para vShipped.
*
* @param vShipped Fecha de preparacion de mercancia
* @param vAddressFk Id de consignatario, %NULL para recogida
* @param vAgencyModeFk Id agencia
* @param vWarehouseFk vWarehouseFk
* @table tmp.zoneGetLanded Datos de recepción
*/
CALL zone_getFromGeo(address_getGeo(vAddressFk));
CALL zone_getOptionsForLanding(vShipped);
DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded;
CREATE TEMPORARY TABLE tmp.zoneGetLanded
ENGINE = MEMORY
SELECT vWarehouseFk warehouseFk,
TIMESTAMPADD(DAY,zo.travelingDays, vShipped) landed,
zo.zoneFk
FROM tmp.zoneOption zo
JOIN zone z ON z.id = zo.zoneFk
JOIN zoneWarehouse zw ON zw.zoneFk = z.id
WHERE agencyModeFk = vAgencyModeFk
AND zw.warehouseFk = vWarehouseFk;
DROP TEMPORARY TABLE
tmp.zone,
tmp.zoneOption;
END$$
DELIMITER ;

View File

@ -1,41 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zone_getShippedWarehouse`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT)
BEGIN
/**
* Devuelve la ­nima fecha de envío para cada warehouse
*
* @param vLanded La fecha de recepcion
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id de la agencia
* @return tmp.zoneGetShipped
*/
CALL zone_getFromGeo(address_getGeo(vAddressFk));
CALL zone_getOptionsForLanding(vLanded);
DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped;
CREATE TEMPORARY TABLE tmp.zoneGetShipped
ENGINE = MEMORY
SELECT * FROM (
SELECT zo.zoneFk,
TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped,
zw.warehouseFk,
z.agencyModeFk
FROM tmp.zoneOption zo
JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk
JOIN zone z ON z.id = zo.zoneFk
WHERE z.agencyModeFk = vAgencyModeFk
ORDER BY shipped) t
GROUP BY warehouseFk;
DROP TEMPORARY TABLE
tmp.zone,
tmp.zoneOption;
END$$
DELIMITER ;

View File

@ -1,42 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zone_getWarehouse`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT)
BEGIN
/**
* Devuelve el listado de agencias disponibles para la fecha,
* dirección y almacén pasados.
*
* @param vAddress
* @param vWarehouse warehouse
* @param vLanded Fecha de recogida
* @select Listado de agencias disponibles
*/
CALL zone_getFromGeo(address_getGeo(vAddress));
CALL zone_getOptionsForLanding(vLanded);
SELECT am.id agencyModeFk,
am.name agencyMode,
am.description,
am.deliveryMethodFk,
TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped,
zw.warehouseFk,
z.id zoneFk
FROM tmp.zoneOption zo
JOIN zone z ON z.id = zo.zoneFk
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk
WHERE zw.warehouseFk
GROUP BY z.agencyModeFk
ORDER BY agencyMode;
DROP TEMPORARY TABLE
tmp.zone,
tmp.zoneOption;
END$$
DELIMITER ;

View File

@ -1,22 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `vn`.`zoneGetAgency`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetAgency`(vAddress INT, vLanded DATE)
BEGIN
/**
* Devuelve el listado de agencias disponibles para la fecha
* y dirección pasadas.
*
* @param vAddress Id de dirección de envío, %NULL si es recogida
* @param vDate Fecha de recogida
* @select Listado de agencias disponibles
*/
CALL zone_getAgency(vAddress,vLanded);
END$$
DELIMITER ;
;

View File

@ -1,3 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `vn`.`zoneGetFirstShipped`;

View File

@ -1,20 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zoneGetLanded`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddress INT, vAgencyMode INT, vWarehouse INT)
BEGIN
/**
* Devuelve una tabla temporal con el dia de recepcion para vShipped.
*
* @param vShipped Fecha de preparacion de mercancia
* @param vAddress Id de consignatario, %NULL para recogida
* @param vAgencyMode Id agencia
* @table tmp.zoneGetLanded Datos de recepción
*/
CALL zone_getLanded(vShipped,vAddress,vAgencyMode,vWarehouse);
END$$
DELIMITER ;

View File

@ -1,24 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zoneGetShipped`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT)
BEGIN
/**
* OBSOLETO usar zone_getShippedWarehouse
* Devuelve la mínima fecha de envía para cada warehouse
*
* @param vLanded La fecha de recepcion
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id de la agencia
* @return tmp.zoneGetShipped
*/
CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk);
SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouseFk;
DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded;
END$$
DELIMITER ;

View File

@ -1,20 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zoneGetShippedWarehouse`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT)
BEGIN
/**
* Devuelve la mínima fecha de envío para cada warehouse
*
* @param vLanded La fecha de recepcion
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id de la agencia
* @return tmp.zoneGetShipped
*/
CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk);
END$$
DELIMITER ;

View File

@ -1,67 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zone_getOptionsForLanding`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE)
BEGIN
/**
* Gets computed options for the passed zones and delivery date.
*
* @table tmp.zones(id) The zones ids
* @param vLanded The delivery date
* @return tmp.zoneOption The computed options
*/
DECLARE vHour TIME DEFAULT TIME(NOW());
DROP TEMPORARY TABLE IF EXISTS tTemp;
CREATE TEMPORARY TABLE tTemp
ENGINE = MEMORY
SELECT t.id zoneFk,
IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`,
IFNULL(e.travelingDays, z.travelingDays) travelingDays,
IFNULL(e.price, z.price) price,
IFNULL(e.bonus, z.bonus) bonus,
CASE
WHEN e.`type` = 'day'
THEN 1
WHEN e.`type` = 'range'
THEN 2
ELSE 3
END specificity
FROM tmp.zone t
JOIN zone z ON z.id = t.id
JOIN zoneEvent e ON e.zoneFk = t.id
WHERE (
e.`type` = 'day'
AND e.dated = vLanded
) OR (
e.`type` != 'day'
AND e.weekDays & (1 << WEEKDAY(vLanded))
AND (e.`started` IS NULL OR vLanded >= e.`started`)
AND (e.`ended` IS NULL OR vLanded <= e.`ended`)
);
DELETE t FROM tTemp t
JOIN zoneExclusion e
ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded;
DELETE FROM tTemp
WHERE (@shipped := TIMESTAMPADD(DAY, -travelingDays, vLanded)) < CURDATE()
OR @shipped = CURDATE() AND vHour > `hour`;
DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption;
CREATE TEMPORARY TABLE tmp.zoneOption
ENGINE = MEMORY
SELECT *
FROM (
SELECT * FROM tTemp
ORDER BY zoneFk, specificity
) t
GROUP BY zoneFk;
DROP TEMPORARY TABLE tTemp;
END$$
DELIMITER ;

View File

@ -1,76 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zone_getOptionsForShipment`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForShipment`(vShipped DATE)
BEGIN
/**
* Gets computed options for the passed zones and shipping date.
*
* @table tmp.zones(id) The zones ids
* @param vShipped The shipping date
* @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options
*/
DROP TEMPORARY TABLE IF EXISTS tLandings;
CREATE TEMPORARY TABLE tLandings
(INDEX (eventFk))
ENGINE = MEMORY
SELECT e.id eventFk,
@travelingDays := IFNULL(e.travelingDays, z.travelingDays) travelingDays,
TIMESTAMPADD(DAY, @travelingDays, vShipped) landed
FROM tmp.zone t
JOIN zone z ON z.id = t.id
JOIN zoneEvent e ON e.zoneFk = t.id;
DROP TEMPORARY TABLE IF EXISTS tTemp;
CREATE TEMPORARY TABLE tTemp
ENGINE = MEMORY
SELECT t.id zoneFk,
IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`,
IFNULL(e.price, z.price) price,
IFNULL(e.bonus, z.bonus) bonus,
CASE
WHEN e.`type` = 'day'
THEN 1
WHEN e.`type` = 'range'
THEN 2
ELSE 3
END specificity,
l.travelingDays,
l.landed
FROM tmp.zone t
JOIN zone z ON z.id = t.id
JOIN zoneEvent e ON e.zoneFk = t.id
JOIN tLandings l ON l.eventFk = e.id
WHERE (
e.`type` = 'day'
AND e.`dated` = l.landed
) OR (
e.`type` != 'day'
AND e.weekDays & (1 << WEEKDAY(l.landed))
AND (e.`started` IS NULL OR l.landed >= e.`started`)
AND (e.`ended` IS NULL OR l.landed <= e.`ended`)
);
DELETE t FROM tTemp t
JOIN zoneExclusion e
ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed;
DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption;
CREATE TEMPORARY TABLE tmp.zoneOption
ENGINE = MEMORY
SELECT *
FROM (
SELECT * FROM tTemp
ORDER BY zoneFk, specificity
) t
GROUP BY zoneFk;
DROP TEMPORARY TABLE
tTemp,
tLandings;
END$$
DELIMITER ;

View File

@ -1 +0,0 @@
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Claim', 'updateClaimAction', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant');

View File

@ -1,2 +0,0 @@
UPDATE `vn`.`claimState` SET `roleFk` = '21' WHERE (`id` = '3');
UPDATE `vn`.`claimState` SET `roleFk` = '21' WHERE (`id` = '5');

View File

@ -1,15 +0,0 @@
CREATE
OR REPLACE ALGORITHM = UNDEFINED
DEFINER = `root`@`%`
SQL SECURITY DEFINER
VIEW `vn`.`component` AS
SELECT
`t`.`Id_Componente` AS `id`,
`t`.`Componente` AS `name`,
`t`.`tarifa_componentes_series_id` AS `typeFk`,
`t`.`tarifa_class` AS `classRate`,
`t`.`tax` AS `tax`,
`t`.`is_renewable` AS `isRenewable`,
`t`.`code` AS `code`
FROM
`bi`.`tarifa_componentes` `t`;

View File

@ -1,2 +0,0 @@
UPDATE vn.department SET lft = NULL, rgt = NULL;

View File

@ -1,37 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `department_calcTree`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTree`()
BEGIN
/**
* Calculates the #path, #lft, #rgt, #sons and #depth columns of
* the #department table. To build the tree, it uses the #parentFk
* column.
*/
DECLARE vIndex INT DEFAULT 0;
DECLARE vSons INT;
DROP TEMPORARY TABLE IF EXISTS tNestedTree;
CREATE TEMPORARY TABLE tNestedTree
SELECT id, path, lft, rgt, depth, sons
FROM department LIMIT 0;
SET max_sp_recursion_depth = 5;
CALL department_calcTreeRec(NULL, '/', 0, vIndex, vSons);
SET max_sp_recursion_depth = 0;
UPDATE department z
JOIN tNestedTree t ON t.id = z.id
SET z.path = t.path,
z.lft = t.lft,
z.rgt = t.rgt,
z.depth = t.depth,
z.sons = t.sons;
DROP TEMPORARY TABLE tNestedTree;
END$$
DELIMITER ;

View File

@ -1,75 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `department_calcTreeRec`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTreeRec`(
vSelf INT,
vPath VARCHAR(255),
vDepth INT,
INOUT vIndex INT,
OUT vSons INT
)
BEGIN
/**
* Calculates and sets the #path, #lft, #rgt, #sons and #depth
* columns for all children of the passed node. Once calculated
* the last node rgt index and the number of sons are returned.
* To update it's children, this procedure calls itself recursively
* for each one.
*
* @vSelf The node identifier
* @vPath The initial path
* @vDepth The initial depth
* @vIndex The initial lft index
* @vSons The number of direct sons
*/
DECLARE vChildFk INT;
DECLARE vLft INT;
DECLARE vMySons INT;
DECLARE vDone BOOL;
DECLARE vChildren CURSOR FOR
SELECT id FROM department
WHERE (vSelf IS NULL AND parentFk IS NULL)
OR (vSelf IS NOT NULL AND parentFk = vSelf);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vSons = 0;
OPEN vChildren;
myLoop: LOOP
SET vDone = FALSE;
FETCH vChildren INTO vChildFk;
IF vDone THEN
LEAVE myLoop;
END IF;
SET vIndex = vIndex + 1;
SET vLft = vIndex;
SET vSons = vSons + 1;
CALL department_calcTreeRec(
vChildFk,
CONCAT(vPath, vChildFk, '/'),
vDepth + 1,
vIndex,
vMySons
);
SET vIndex = vIndex + 1;
INSERT INTO tNestedTree
SET id = vChildFk,
path = vPath,
lft = vLft,
rgt = vIndex,
depth = vDepth,
sons = vMySons;
END LOOP;
CLOSE vChildren;
END$$
DELIMITER ;

View File

@ -1,35 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `department_doCalc`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `department_doCalc`()
proc: BEGIN
/**
* Recalculates the department tree.
*/
DECLARE vIsChanged BOOL;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK('vn.department_doCalc');
RESIGNAL;
END;
IF !GET_LOCK('vn.department_doCalc', 0) THEN
LEAVE proc;
END IF;
SELECT isChanged INTO vIsChanged
FROM department_recalc;
IF vIsChanged THEN
UPDATE department_recalc SET isChanged = FALSE;
CALL vn.department_calcTree;
END IF;
DO RELEASE_LOCK('vn.department_doCalc');
END$$
DELIMITER ;

View File

@ -1,84 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `department_getLeaves`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `department_getLeaves`(
vParentFk INT,
vSearch VARCHAR(255)
)
BEGIN
DECLARE vIsNumber BOOL;
DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != '';
DROP TEMPORARY TABLE IF EXISTS tNodes;
CREATE TEMPORARY TABLE tNodes
(UNIQUE (id))
ENGINE = MEMORY
SELECT id FROM department LIMIT 0;
IF vIsSearch THEN
SET vIsNumber = vSearch REGEXP '^[0-9]+$';
INSERT INTO tNodes
SELECT id FROM department
WHERE (vIsNumber AND `name` = vSearch)
OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%'))
LIMIT 1000;
END IF;
IF vParentFk IS NULL THEN
DROP TEMPORARY TABLE IF EXISTS tChilds;
CREATE TEMPORARY TABLE tChilds
ENGINE = MEMORY
SELECT id FROM tNodes;
DROP TEMPORARY TABLE IF EXISTS tParents;
CREATE TEMPORARY TABLE tParents
ENGINE = MEMORY
SELECT id FROM department LIMIT 0;
myLoop: LOOP
DELETE FROM tParents;
INSERT INTO tParents
SELECT parentFk id
FROM department g
JOIN tChilds c ON c.id = g.id
WHERE g.parentFk IS NOT NULL;
INSERT IGNORE INTO tNodes
SELECT id FROM tParents;
IF ROW_COUNT() = 0 THEN
LEAVE myLoop;
END IF;
DELETE FROM tChilds;
INSERT INTO tChilds
SELECT id FROM tParents;
END LOOP;
DROP TEMPORARY TABLE
tChilds,
tParents;
END IF;
IF !vIsSearch THEN
INSERT IGNORE INTO tNodes
SELECT id FROM department
WHERE parentFk <=> vParentFk;
END IF;
SELECT d.id,
d.`name`,
d.parentFk,
d.sons
FROM department d
JOIN tNodes n ON n.id = d.id
ORDER BY depth, `name`;
DROP TEMPORARY TABLE tNodes;
END$$
DELIMITER ;

View File

@ -1,10 +0,0 @@
ALTER TABLE `vn`.`route`
ADD COLUMN `zoneFk` INT NULL AFTER `description`,
ADD INDEX `fk_route_1_idx` (`zoneFk` ASC);
;
ALTER TABLE `vn`.`route`
ADD CONSTRAINT `fk_route_1`
FOREIGN KEY (`zoneFk`)
REFERENCES `vn`.`zone` (`id`)
ON DELETE RESTRICT
ON UPDATE CASCADE;

View File

@ -1 +0,0 @@
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('UserPhone', '*', 'WRITE', 'ALLOW', 'ROLE', 'employee');

View File

@ -1,18 +0,0 @@
CREATE TABLE `vn`.`travelLog` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`originFk` int(10) unsigned NOT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL,
`creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`description` text CHARACTER SET utf8,
`changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
`oldInstance` text COLLATE utf8_unicode_ci,
`newInstance` text COLLATE utf8_unicode_ci,
`changedModelId` int(11) DEFAULT NULL,
`changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `originFk` (`originFk`),
KEY `userFk` (`userFk`),
CONSTRAINT `travelLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn`.`travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

View File

@ -1,6 +0,0 @@
CREATE TABLE `vn`.`packagingConfig` (
`id` INT NOT NULL AUTO_INCREMENT,
`upperGap` INT NOT NULL,
PRIMARY KEY (`id`));
INSERT INTO `vn`.`packagingConfig` (`upperGap`) VALUES ('10');

View File

@ -1,18 +0,0 @@
CREATE TABLE `vn`.`userLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`originFk` int(10) unsigned NOT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL,
`creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`description` text CHARACTER SET utf8,
`changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
`oldInstance` text COLLATE utf8_unicode_ci,
`newInstance` text COLLATE utf8_unicode_ci,
`changedModelId` int(11) DEFAULT NULL,
`changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `originFk` (`originFk`),
KEY `userFk` (`userFk`),
CONSTRAINT `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

View File

@ -1,9 +0,0 @@
CREATE TABLE `vn`.`userPhoneType` (
`code` VARCHAR(45) NOT NULL,
`description` VARCHAR(255) NULL,
PRIMARY KEY (`code`));
INSERT INTO `vn`.`userPhoneType` (`code`, `description`) VALUES ('businessPhone', 'Telefono de empresa del usuario');
INSERT INTO `vn`.`userPhoneType` (`code`, `description`) VALUES ('personalPhone', 'Telefono personal del usuario');

View File

@ -1,23 +0,0 @@
CREATE TABLE `vn`.`userPhone` (
`id` INT NOT NULL AUTO_INCREMENT,
`userFk` INT(10) UNSIGNED NOT NULL,
`typeFk` VARCHAR(45) NOT NULL,
`phone` VARCHAR(25) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `UserFk_Phone` (`userFk` ASC, `typeFk` ASC, `phone` ASC));
ALTER TABLE `vn`.`userPhone`
ADD CONSTRAINT `fgnTypeFk`
FOREIGN KEY (typeFk)
REFERENCES `vn`.`userPhoneType` (code)
ON DELETE RESTRICT
ON UPDATE CASCADE;
ALTER TABLE `vn`.`userPhone`
ADD CONSTRAINT `fgnUserFk`
FOREIGN KEY (userFk)
REFERENCES `account`.`user` (id)
ON DELETE CASCADE
ON UPDATE CASCADE;

View File

@ -1,17 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `vn`.`ticketCalculate`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculate__`(
vLanded DATE,
vAddressFk INT,
vAgencyModeFk INT)
proc: BEGIN
-- OBSOLETO utilizar catalog_calculate
CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk);
END$$
DELIMITER ;
;

View File

@ -1,63 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `available_calc`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `available_calc`(
vDate DATE,
vAddress INT,
vAgencyMode INT)
BEGIN
/**
* Calculates the available for all available stores
* according to the given parameters.
*
* @param vDate The delivery date
* @param vAddress The delivery address id
* @param vAgencyMode The shipping agency
* @return tmp.availableCalc(calcFk) The available cache ids
*/
DECLARE vCalcFk INT;
DECLARE vShipment DATE;
DECLARE vWarehouse INT;
DECLARE vDone BOOL;
DECLARE cWarehouses CURSOR FOR
SELECT warehouseFk, shipped FROM tmp.zoneGetShipped;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
-- Establecemos los almacenes y las fechas que van a entrar al disponible
CALL vn.zone_getShippedWarehouse(vDate, vAddress, vAgencyMode);
DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc;
CREATE TEMPORARY TABLE tmp.availableCalc(
calcFk INT UNSIGNED,
PRIMARY KEY (calcFk)
)
ENGINE = MEMORY;
OPEN cWarehouses;
l: LOOP
SET vDone = FALSE;
FETCH cWarehouses INTO vWarehouse, vShipment;
IF vDone THEN
LEAVE l;
END IF;
CALL `cache`.available_refresh(vCalcFk, FALSE, vWarehouse, vShipment);
INSERT IGNORE INTO tmp.availableCalc
SET calcFk = vCalcFk;
END LOOP;
CLOSE cWarehouses;
DROP TEMPORARY TABLE tmp.zoneGetShipped;
END$$
DELIMITER ;

View File

@ -1,119 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `catalog_calculate`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate`(
vLanded DATE,
vAddressFk INT,
vAgencyModeFk INT)
proc: BEGIN
/**
* Calcula los articulos disponibles y sus precios
*
* @table tmp.item(itemFk) Listado de artículos a calcular
* @param vLanded Fecha de recepcion de mercancia
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id de la agencia
* @return tmp.ticketCalculateItem(itemFk, available, producer,
* item, size, stems, category, inkFk, image, origin, price)
* @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk)
* @return tmp.ticketComponent
* @return tmp.ticketComponentPrice
* @return tmp.zoneGetShipped
**/
DECLARE vAvailableCalc INT;
DECLARE vShipped DATE;
DECLARE vClient INT;
DECLARE vWarehouseFk SMALLINT;
DECLARE vZoneFk INT;
DECLARE vDone BOOL;
DECLARE cTravelTree CURSOR FOR
SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-- Establece los almacenes y las fechas que van a entrar al disponible
SELECT clientFk INTO vClient
FROM address WHERE id = vAddressFk;
CALL vn.zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot(
`warehouseFk` smallint(5) unsigned NOT NULL,
`itemFk` int(11) NOT NULL,
`available` double DEFAULT NULL,
`buyFk` int(11) DEFAULT NULL,
`fix` tinyint(3) unsigned DEFAULT '0',
KEY `itemFk` (`itemFk`),
KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
OPEN cTravelTree;
l: LOOP
SET vDone = FALSE;
FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped;
IF vDone THEN
LEAVE l;
END IF;
CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped);
CALL buyUltimate (vWarehouseFk, vShipped);
INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk)
SELECT vWarehouseFk,
i.item_id,
IFNULL(i.available, 0),
bu.buyFk
FROM `cache`.available i
JOIN tmp.item br ON br.itemFk = i.item_id
LEFT JOIN item it ON it.id = i.item_id
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id
WHERE i.calc_id = vAvailableCalc
AND it.id != 100
AND i.available > 0;
DROP TEMPORARY TABLE tmp.buyUltimate;
END LOOP;
CLOSE cTravelTree;
CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem;
CREATE TEMPORARY TABLE tmp.ticketCalculateItem
ENGINE = MEMORY
SELECT
b.itemFk,
SUM(b.available) available,
p.name producer,
i.name item,
i.size size,
i.stems,
i.category,
i.inkFk,
i.image,
o.code origin,
bl.price,
bl.priceKg
FROM tmp.ticketLot b
JOIN item i ON b.itemFk = i.id
LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible
JOIN origin o ON o.id = i.originFk
JOIN (
SELECT MIN(price) price, itemFk, priceKg
FROM tmp.ticketComponentPrice
GROUP BY itemFk
) bl ON bl.itemFk = b.itemFk
GROUP BY b.itemFk;
END$$
DELIMITER ;

View File

@ -1,88 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `ticketCalculateClon`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT)
BEGIN
/*
* @vTicketNew id del nuevo ticket clonado
* @vTicketOld id ticket original, a partir del qual se clonara el nuevo
* Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo
*/
DECLARE vShipped DATE;
DECLARE vClient INT;
DECLARE vWarehouse SMALLINT;
DECLARE vAgencyMode INT;
DECLARE vAddress INT;
DECLARE vLanded DATE;
DECLARE vAgency INT;
DECLARE vZoneFk INT;
REPLACE INTO orderTicket(orderFk,ticketFk)
SELECT orderFk, vTicketNew
FROM orderTicket
WHERE ticketFk = vTicketOld;
SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk
INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk
FROM vn.agencyMode a
JOIN vn.ticket t ON t.agencyModeFk = a.id
WHERE t.id = vTicketNew;
IF vLanded IS NULL THEN
CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse);
UPDATE ticket t
JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk
SET t.landed = zgl.landed,
t.zone = zgl.zoneFk
WHERE t.id = vTicketNew;
SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1;
DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded;
END IF;
-- rellena la tabla tmp.buyUltimate con la ultima compra
CALL buyUltimate(vWarehouse, vShipped);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot
SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk
FROM sale s
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk;
CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode);
-- Bionizamos lineas con Preu = 0
DROP TEMPORARY TABLE IF EXISTS tmp.sale;
CREATE TEMPORARY TABLE tmp.sale
(PRIMARY KEY (saleFk)) ENGINE = MEMORY
SELECT s.id saleFk, vWarehouse warehouseFk
FROM sale s
JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew AND s.price = 0;
CALL ticketComponentUpdateSale(1);
-- Bionizamos lineas con Preu > 0
DROP TEMPORARY TABLE IF EXISTS tmp.sale;
CREATE TEMPORARY TABLE tmp.sale
(PRIMARY KEY (saleFk)) ENGINE = MEMORY
SELECT s.id saleFk, vWarehouse warehouseFk
FROM sale s
JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew
AND s.price > 0;
CALL ticketComponentUpdateSale(6);
-- Log
CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket');
-- Limpieza
DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate;
DROP TEMPORARY TABLE IF EXISTS tmp.sale;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded;
END$$
DELIMITER ;

View File

@ -1,262 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `vn`.`ticketComponentCalculate`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate__`(
vAddressFk INT,
vAgencyModeFk INT)
proc: BEGIN
-- OBSOLETO usar catalog_componentCalculate
/**
* Calcula los componentes de un ticket
*
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id del modo de agencia
* @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice,
* packing, grouping, groupingMode, buyFk, typeFk)
* @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price)
*/
DECLARE vClientFk INT;
DECLARE vGeneralInflationCoefficient INT DEFAULT 1;
DECLARE vMinimumDensityWeight INT DEFAULT 167;
DECLARE vBoxFreightItem INT DEFAULT 71;
DECLARE vBoxVolume BIGINT; -- DEFAULT 138000;
DECLARE vSpecialPriceComponent INT DEFAULT 10;
DECLARE vDeliveryComponent INT DEFAULT 15;
DECLARE vRecoveryComponent INT DEFAULT 17;
DECLARE vSellByPacketComponent INT DEFAULT 22;
DECLARE vBuyValueComponent INT DEFAULT 28;
DECLARE vMarginComponent INT DEFAULT 29;
DECLARE vDiscountLastItemComponent INT DEFAULT 32;
DECLARE vExtraBaggedComponent INT DEFAULT 38;
DECLARE vManaAutoComponent INT DEFAULT 39;
SELECT volume INTO vBoxVolume
FROM vn.packaging
WHERE id = '94';
SELECT clientFk INTO vClientFK
FROM address
WHERE id = vAddressFk;
SET @rate2 := 0;
SET @rate3 := 0;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate;
CREATE TEMPORARY TABLE tmp.ticketComponentCalculate
(PRIMARY KEY (itemFk, warehouseFk))
ENGINE = MEMORY
SELECT
tl.itemFk, tl.warehouseFk, tl.available,
IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2,
IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3,
IFNULL(pf.rate3, 0) AS minPrice,
IFNULL(pf.packing, b.packing) packing,
IFNULL(pf.`grouping`, b.`grouping`) `grouping`,
ABS(IFNULL(pf.box, b.groupingMode)) groupingMode,
tl.buyFk,
i.typeFk,
IF(i.hasKgPrice,b.weight / b.packing, NULL) weightGrouping
FROM tmp.ticketLot tl
JOIN buy b ON b.id = tl.buyFk
JOIN item i ON i.id = tl.itemFk
JOIN itemType it ON it.id = i.typeFk
LEFT JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk
LEFT JOIN (
SELECT * FROM (
SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, aho.warehouseFk
FROM priceFixed pf
JOIN tmp.zoneGetShipped aho ON pf.warehouseFk = aho.warehouseFk OR pf.warehouseFk = 0
WHERE aho.shipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC
) tpf
GROUP BY tpf.itemFk, tpf.warehouseFk
) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk
WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
CREATE TEMPORARY TABLE tmp.ticketComponent (
`warehouseFk` INT UNSIGNED NOT NULL,
`itemFk` INT NOT NULL,
`componentFk` INT UNSIGNED NOT NULL,
`cost` DECIMAL(10,4) NOT NULL,
INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC));
INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
SELECT
tcc.warehouseFk,
tcc.itemFk,
vBuyValueComponent,
b.buyingValue + b.freightValue + b.packageValue + b.comissionValue
FROM tmp.ticketComponentCalculate tcc
JOIN buy b ON b.id = tcc.buyFk;
INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
SELECT
tcc.warehouseFk,
tcc.itemFk,
vMarginComponent,
tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue
FROM tmp.ticketComponentCalculate tcc
JOIN buy b ON b.id = tcc.buyFk;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase;
CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY
SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk
FROM tmp.ticketComponent tc
GROUP BY tc.itemFk, warehouseFk;
INSERT INTO tmp.ticketComponent
SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3)
FROM tmp.ticketComponentBase tcb
JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk
WHERE cr.recobro > 0.009;
INSERT INTO tmp.ticketComponent
SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto
FROM tmp.ticketComponentBase tcb
JOIN `client` c on c.id = vClientFk
JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador
WHERE ms.prices_modifier_activated
HAVING manaAuto <> 0;
INSERT INTO tmp.ticketComponent
SELECT tcb.warehouseFk,
tcb.itemFk,
cr.id,
GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3)
FROM tmp.ticketComponentBase tcb
JOIN componentRate cr
JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk
LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL;
INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3
FROM tmp.ticketComponentCalculate tcc
JOIN buy b ON b.id = tcc.buyFk
LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
WHERE sp.value IS NULL;
INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFK,
tcc.itemFk,
vDeliveryComponent,
vGeneralInflationCoefficient
* ROUND((
i.compression
* r.cm3
* IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1)
* IFNULL((z.price - z.bonus)
* 1/*amz.inflation*/ , 50)) / vBoxVolume, 4
) cost
FROM tmp.ticketComponentCalculate tcc
JOIN item i ON i.id = tcc.itemFk
JOIN agencyMode am ON am.id = vAgencyModeFk
JOIN `address` a ON a.id = vAddressFk
JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = tcc.warehouseFk
JOIN zone z ON z.id = zgs.id
LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk
AND r.Id_Article = tcc.itemFk
HAVING cost <> 0;
IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN
INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost
FROM tmp.ticketComponentCalculate tcc
JOIN vn.addressForPackaging ap
WHERE ap.addressFk = vAddressFk;
END IF;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy;
CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY
SELECT * FROM tmp.ticketComponent;
INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFk,
tcc.itemFk,
vSpecialPriceComponent,
sp.value - SUM(tcc.cost) sumCost
FROM tmp.ticketComponentCopy tcc
JOIN componentRate cr ON cr.id = tcc.componentFk
JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk
WHERE cr.classRate IS NULL
GROUP BY tcc.itemFk, tcc.warehouseFk
HAVING ABS(sumCost) > 0.001;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum;
CREATE TEMPORARY TABLE tmp.ticketComponentSum
(INDEX (itemFk, warehouseFk))
ENGINE = MEMORY
SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate
FROM tmp.ticketComponent tc
JOIN componentRate cr ON cr.id = tc.componentFk
GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate;
CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY
SELECT tcc.warehouseFk,
tcc.itemFk,
1 rate,
IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`,
CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price,
CAST(SUM(tcs.sumCost) / weightGrouping AS DECIMAL(10,2)) priceKg
FROM tmp.ticketComponentCalculate tcc
JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
AND tcs.warehouseFk = tcc.warehouseFk
WHERE IFNULL(tcs.classRate, 1) = 1
AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0)
GROUP BY tcs.warehouseFk, tcs.itemFk;
INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
SELECT
tcc.warehouseFk,
tcc.itemFk,
2 rate,
tcc.packing `grouping`,
SUM(tcs.sumCost) price,
SUM(tcs.sumCost) / weightGrouping priceKg
FROM tmp.ticketComponentCalculate tcc
JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
AND tcs.warehouseFk = tcc.warehouseFk
WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2
AND tcc.packing > 0 AND tcc.available >= tcc.packing)
GROUP BY tcs.warehouseFk, tcs.itemFk;
INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
SELECT
tcc.warehouseFk,
tcc.itemFk,
3 rate,
tcc.available `grouping`,
SUM(tcs.sumCost) price,
SUM(tcs.sumCost) / weightGrouping priceKg
FROM tmp.ticketComponentCalculate tcc
JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
AND tcs.warehouseFk = tcc.warehouseFk
WHERE IFNULL(tcs.classRate, 3) = 3
GROUP BY tcs.warehouseFk, tcs.itemFk;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice;
CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY
SELECT * FROM (
SELECT * FROM tmp.ticketComponentRate ORDER BY price
) t
GROUP BY itemFk, warehouseFk, `grouping`;
DROP TEMPORARY TABLE
tmp.ticketComponentCalculate,
tmp.ticketComponentSum,
tmp.ticketComponentBase,
tmp.ticketComponentRate,
tmp.ticketComponentCopy;
END$$
DELIMITER ;
;

View File

@ -1,88 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `ticketCreateWithUser`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`(
vClientId INT
,vShipped DATE
,vWarehouseFk INT
,vCompanyFk INT
,vAddressFk INT
,vAgencyModeFk INT
,vRouteFk INT
,vlanded DATE
,vUserId INT
,OUT vNewTicket INT)
BEGIN
DECLARE vZoneFk INT;
IF vClientId IS NULL THEN
CALL util.throw ('CLIENT_NOT_ESPECIFIED');
END IF;
IF NOT vAddressFk OR vAddressFk IS NULL THEN
SELECT id INTO vAddressFk
FROM address
WHERE clientFk = vClientId AND isDefaultAddress;
END IF;
IF vAgencyModeFk IS NOT NULL THEN
CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk);
SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped
WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1;
IF vZoneFk IS NULL OR vZoneFk = 0 THEN
CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS');
END IF;
END IF;
INSERT INTO ticket (
clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
warehouseFk,
routeFk,
companyFk,
landed,
zoneFk
)
SELECT
vClientId,
vShipped,
a.id,
vAgencyModeFk,
a.nickname,
vWarehouseFk,
IF(vRouteFk,vRouteFk,NULL),
vCompanyFk,
vlanded,
vZoneFk
FROM address a
JOIN agencyMode am ON am.id = a.agencyModeFk
WHERE a.id = vAddressFk;
SET vNewTicket = LAST_INSERT_ID();
INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
SELECT vNewTicket, ao.observationTypeFk, ao.description
FROM addressObservation ao
JOIN address a ON a.id = ao.addressFk
WHERE a.id = vAddressFk;
INSERT INTO vn.ticketLog
SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket);
IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN
INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
SELECT id, vNewTicket, getWorker()
FROM state
WHERE `code` = 'DELIVERED';
END IF;
END$$
DELIMITER ;

View File

@ -1,90 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `ticketCreateWithoutZone`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`(
vClientId INT
,vShipped DATE
,vWarehouseFk INT
,vCompanyFk INT
,vAddressFk INT
,vAgencyModeFk INT
,vRouteFk INT
,vlanded DATE
,vUserId INT
,OUT vNewTicket INT)
BEGIN
DECLARE vZoneFk INT;
IF vClientId IS NULL THEN
CALL util.throw ('CLIENT_NOT_ESPECIFIED');
END IF;
IF NOT vAddressFk OR vAddressFk IS NULL THEN
SELECT id INTO vAddressFk
FROM address
WHERE clientFk = vClientId AND isDefaultAddress;
END IF;
IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN
SELECT agencyModeFk INTO vAgencyModeFk
FROM address
WHERE clientFk = vClientId AND isDefaultAddress;
END IF;
CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk);
SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped
WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1;
INSERT INTO vn2008.Tickets (
Id_Cliente,
Fecha,
Id_Consigna,
Id_Agencia,
Alias,
warehouse_id,
Id_Ruta,
empresa_id,
landing,
zoneFk
)
SELECT
vClientId,
vShipped,
a.id,
IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk),
a.nickname,
vWarehouseFk,
IF(vRouteFk,vRouteFk,NULL),
vCompanyFk,
vlanded,
vZoneFk
FROM address a
JOIN agencyMode am ON am.id = a.agencyModeFk
WHERE a.id = vAddressFk;
SET vNewTicket = LAST_INSERT_ID();
INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
SELECT vNewTicket, ao.observationTypeFk, ao.description
FROM addressObservation ao
JOIN address a ON a.id = ao.addressFk
WHERE a.id = vAddressFk;
-- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket));
INSERT INTO vn.ticketLog
SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket);
IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN
INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
SELECT id, vNewTicket, getWorker()
FROM state
WHERE `code` = 'DELIVERED';
END IF;
END$$
DELIMITER ;

View File

@ -1,31 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `catalog_calcFromItem`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calcFromItem`(
vLanded DATE,
vAddressFk INT,
vAgencyModeFk INT,
vItemFk INT)
BEGIN
/**
* Calculates available and price for a single item.
*
* @param vItemFk The item id
* @return tmp.ticketCalculateItem
* @return tmp.ticketComponentPrice
* @return tmp.ticketComponent
* @return tmp.ticketLot
* @return tmp.zoneGetShipped
*/
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
ENGINE = MEMORY
SELECT vItemFk itemFk;
CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk);
DROP TEMPORARY TABLE tmp.item;
END$$
DELIMITER ;

View File

@ -1,11 +0,0 @@
USE `vn`;
CREATE TABLE `vn`.`chatConfig` (
`id` INT NOT NULL AUTO_INCREMENT,
`uri` VARCHAR(255) NOT NULL,
`user` VARCHAR(50) NOT NULL,
`password` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`));
INSERT INTO `vn`.`chatConfig` (`uri`, `user`, `password`) VALUES ('https://chat.verdnatura.es/api/v1', 'VnBot', 'Ub606cux7op.');

View File

@ -1,51 +0,0 @@
DROP TRIGGER IF EXISTS `vn`.`client_beforeUpdate`;
DELIMITER $$
CREATE DEFINER=`root`@`%` TRIGGER `vn`.`client_beforeUpdate`
BEFORE UPDATE ON `client`
FOR EACH ROW
BEGIN
DECLARE vText VARCHAR(255) DEFAULT NULL;
-- Comprueba que el formato de los teléfonos es válido
IF !(NEW.phone <=> OLD.phone) THEN
CALL pbx.phone_isValid(NEW.phone);
END IF;
IF !(NEW.mobile <=> OLD.mobile) THEN
CALL pbx.phone_isValid(NEW.mobile);
END IF;
IF !(NEW.fax <=> OLD.fax) THEN
CALL pbx.phone_isValid(NEW.fax);
END IF;
IF NEW.payMethodFk = 4 AND NEW.dueDay = 0 THEN
SET NEW.dueDay = 5;
END IF;
-- Avisar al comercial si ha llegado la documentación sepa/core
IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN
SET vText = 'Sepa de VNL';
END IF;
IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN
SET vText = 'Core de VNL';
END IF;
IF vText IS NOT NULL
THEN
INSERT INTO mail(sender, replyTo, `subject`, body)
SELECT
CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'),
'administracion@verdnatura.es',
CONCAT('Cliente ', NEW.id),
CONCAT('Recibida la documentación: ', vText)
FROM worker w
LEFT JOIN account.user u ON w.userFk = u.id AND u.active
LEFT JOIN account.account ac ON ac.id = u.id
WHERE w.id = NEW.salesPersonFk;
END IF;
END$$
DELIMITER ;

View File

@ -1,75 +0,0 @@
DROP function IF EXISTS `vn`.`clientGetMana`;
DELIMITER $$
CREATE DEFINER=`root`@`%` FUNCTION `vn`.`clientGetMana`(vClient INT) RETURNS decimal(10,2)
DETERMINISTIC
BEGIN
/**
* Devuelve el mana del cliente.
*
* @param vClient Id del cliente
* @return Mana del cliente
*/
DECLARE vMana DECIMAL(10,2);
DECLARE vFromDated DATE;
DECLARE vHasMana BOOLEAN;
DECLARE vManaComponent INT;
DECLARE vAutoManaComponent INT;
DECLARE vManaBank INT;
DECLARE vManaGreugeType INT;
SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana';
SELECT id INTO vManaBank FROM bank WHERE code = 'mana';
SELECT id INTO vManaComponent FROM component WHERE code = 'mana';
SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana';
SELECT COUNT(*) INTO vHasMana
FROM `client` c
WHERE c.id = vClient AND c.typeFk = 'normal';
IF NOT vHasMana THEN
RETURN 0;
END IF;
SELECT max(dated) INTO vFromDated
FROM clientManaCache;
SELECT sum(mana) INTO vMana
FROM
(
SELECT mana
FROM clientManaCache
WHERE clientFk = vClient
AND dated = vFromDated
UNION ALL
SELECT s.quantity * value
FROM ticket t
JOIN address a ON a.id = t.addressFk
JOIN sale s on s.ticketFk = t.id
JOIN saleComponent sc on sc.saleFk = s.id
WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent)
AND t.shipped > vFromDated
AND t.shipped < TIMESTAMPADD(DAY,1,CURDATE())
AND a.clientFk = vClient
UNION ALL
SELECT - amountPaid
FROM receipt r
JOIN `client` c ON c.id = r.clientFk
WHERE r.bankFk = vManaBank
AND r.payed > vFromDated
AND r.payed <= CURDATE()
AND c.id = vClient
UNION ALL
SELECT g.amount
FROM greuge g
JOIN `client` c ON c.id = g.clientFk
WHERE g.greugeTypeFk = vManaGreugeType
AND g.shipped > vFromDated
AND g.shipped <= CURDATE()
AND c.id = vClient
) sub;
RETURN IFNULL(vMana,0);
END$$
DELIMITER ;

View File

@ -1,97 +0,0 @@
DROP procedure IF EXISTS `vn`.`clientPackagingOverstock`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clientPackagingOverstock`(vClientFk INT, vGraceDays INT )
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock;
CREATE TEMPORARY TABLE tmp.clientPackagingOverstock
ENGINE = MEMORY
SELECT itemFk,
sum(GotfromClient) - sum(SenttoClient) as devueltos,
sum(InvoicedtoClient) - sum(InvoicedfromClient) as facturados,
LEAST(
sum(GotfromClient) - sum(SenttoClient),
sum(InvoicedtoClient) - sum(InvoicedfromClient)
) as abonables
FROM
(
SELECT t.*,
IF(@month = month, 0, 1) monthEnd,
@month := month
FROM
(
SELECT x.id as ticketFk,
date(x.shipped) as shipped,
x.itemFk,
IFNULL(cast(sum(x.InvoicedtoClient) as DECIMAL(10,0)),0) InvoicedtoClient,
IFNULL(cast(sum(x.InvoicedfromClient) as DECIMAL(10,0)),0) InvoicedfromClient,
IFNULL(cast(sum(x.SenttoClient) as DECIMAL(10,0)),0) SenttoClient,
IFNULL(cast(sum(x.GotfromClient) as DECIMAL(10,0)),0) GotfromClient,
i.name as concept,
x.refFk as invoice,
month(shipped) month,
x.companyFk
FROM
(
SELECT t.id,
t.shipped,
IFNULL(pe.equivalentFk, s.itemFk) itemFk,
IF(s.quantity > 0, s.quantity, NULL) InvoicedtoClient,
IF(s.quantity < 0, -s.quantity, NULL) InvoicedfromClient,
NULL SenttoClient,
NULL GotfromClient,
t.refFk,
@month := 0 month,
t.companyFk
FROM sale s
JOIN ticket t on t.id = s.ticketFk
JOIN packaging p ON p.itemFk = s.itemFk
LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk
WHERE t.clientFk = vClientFk
AND t.shipped > '2017-11-30'
AND p.isPackageReturnable
UNION ALL
SELECT NULL,
'2017-11-30',
IFNULL(pe.equivalentFk, tps.itemFk) itemFk,
tps.sent InvoicedtoClient,
tps.returned InvoicedfromClient,
NULL SenttoClient,
NULL GotfromClient,
'Histórico',
NULL,
NULL
FROM ticketPackagingStartingStock tps
LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk
WHERE tps.clientFk = vClientFk
AND tps.isForgetable = FALSE
UNION ALL
SELECT t.id,
t.shipped,
IFNULL(pe.equivalentFk, p.itemFk) itemFk,
NULL,
NULL,
IF(tp.quantity > 0 AND t.shipped <= TIMESTAMPADD(DAY, - vGraceDays, CURDATE()), tp.quantity, NULL) SenttoClient,
IF(tp.quantity < 0, -tp.quantity, NULL) GotfromClient,
NULL AS refFk,
NULL,
t.companyFk
FROM ticketPackaging tp
JOIN ticket t on t.id = tp.ticketFk
JOIN packaging p ON p.id = tp.packagingFk
LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk
WHERE t.clientFk = vClientFk
AND t.shipped > '2017-11-21' ) x
JOIN item i ON x.itemFk = i.id
GROUP BY x.id, x.itemFk
) t
ORDER BY itemFk, shipped DESC
) t2
GROUP BY itemFk;
END$$
DELIMITER ;

View File

@ -1,132 +0,0 @@
DROP procedure IF EXISTS `vn`.`clonTravelComplete`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255))
BEGIN
DECLARE vTravelNew INT;
DECLARE vEntryNew INT;
DECLARE vDone BIT DEFAULT 0;
DECLARE vAuxEntryFk INT;
DECLARE vRsEntry CURSOR FOR
SELECT e.id
FROM entry e
JOIN travel t
ON t.id = e.travelFk
WHERE e.travelFk = vTravelFk;
DECLARE vRsBuy CURSOR FOR
SELECT b.*
FROM buy b
JOIN entry e
ON b.entryFk = e.id
WHERE e.travelFk = vTravelNew and b.entryFk=entryNew
ORDER BY e.id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
INSERT INTO travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg)
SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg
FROM travel
WHERE id = vTravelFk;
SET vTravelNew = LAST_INSERT_ID();
SET vDone = 0;
OPEN vRsEntry ;
FETCH vRsEntry INTO vAuxEntryFk;
WHILE NOT vDone DO
INSERT INTO entry (supplierFk,
ref,
isInventory,
isConfirmed,
isOrdered,
isRaid,
commission,
created,
evaNotes,
travelFk,
currencyFk,
companyFk,
gestDocFk,
invoiceInFk)
SELECT supplierFk,
ref,
isInventory,
isConfirmed,
isOrdered,
isRaid,
commission,
created,
evaNotes,
vTravelNew,
currencyFk,
companyFk,
gestDocFk,
invoiceInFk
FROM entry
WHERE id = vAuxEntryFk;
SET vEntryNew = LAST_INSERT_ID();
INSERT INTO buy (entryFk,
itemFk,
quantity,
buyingValue,
packageFk,
stickers,
freightValue,
packageValue,
comissionValue,
packing,
`grouping`,
groupingMode,
location,
price1,
price2,
price3,
minPrice,
producer,
printedStickers,
isChecked)
SELECT vEntryNew,
itemFk,
quantity,
buyingValue,
packageFk,
stickers,
freightValue,
packageValue,
comissionValue,
packing,
`grouping`,
groupingMode,
location,
price1,
price2,
price3,
minPrice,
producer,
printedStickers,
isChecked
FROM buy
WHERE entryFk = vAuxEntryFk;
FETCH vRsEntry INTO vAuxEntryFk;
END WHILE;
CLOSE vRsEntry;
COMMIT;
END$$
DELIMITER ;

View File

@ -1,10 +0,0 @@
USE `vn`;
UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 1);
UPDATE `vn`.`country` SET `ibanLength` = '27' WHERE (`id` = 2);
UPDATE `vn`.`country` SET `ibanLength` = '22' WHERE (`id` = 3);
UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 4);
UPDATE `vn`.`country` SET `ibanLength` = '18' WHERE (`id` = 5);
UPDATE `vn`.`country` SET `ibanLength` = '25' WHERE (`id` = 8);
UPDATE `vn`.`country` SET `ibanLength` = '27' WHERE (`id` = 19);
UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 30);

View File

@ -1,16 +0,0 @@
DELIMITER $$
DROP TRIGGER IF EXISTS `vn`.`creditClassification_BEFORE_UPDATE` $$
CREATE DEFINER=`root`@`%` TRIGGER `vn`.`creditClassification_beforeUpdate` BEFORE UPDATE ON `creditClassification` FOR EACH ROW
BEGIN
IF NEW.client <> OLD.client THEN
CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT');
END IF;
IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN
UPDATE `client` c
SET creditInsurance = 0 WHERE c.id = NEW.client;
END IF;
END$$
DELIMITER ;

View File

@ -1,13 +0,0 @@
DELIMITER $$
DROP TRIGGER IF EXISTS `vn`.`creditInsurance_AFTER_INSERT` $$
CREATE DEFINER=`root`@`%` TRIGGER `vn`.`creditInsurance_afterInsert` AFTER INSERT ON `creditInsurance` FOR EACH ROW
BEGIN
UPDATE `client` c
JOIN vn.creditClassification cc ON cc.client = c.id
SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification;
END$$
DELIMITER ;

View File

@ -1,3 +0,0 @@
USE `vn`;
CREATE DEFINER=`root`@`%` EVENT `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.department_doCalc

View File

@ -1,74 +0,0 @@
DROP procedure IF EXISTS `vn`.`duaInvoiceInBooking`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`duaInvoiceInBooking`(vDuaFk INT)
BEGIN
DECLARE done BOOL DEFAULT FALSE;
DECLARE vInvoiceFk INT;
DECLARE vASIEN BIGINT DEFAULT 0;
DECLARE vCounter INT DEFAULT 0;
DECLARE rs CURSOR FOR
SELECT e.invoiceInFk
FROM entry e
JOIN duaEntry de ON de.entryFk = e.id
JOIN invoiceIn ii ON ii.id = e.invoiceInFk
WHERE de.duaFk = vDuaFk
AND de.customsValue
AND ii.isBooked = FALSE;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN rs;
UPDATE invoiceIn ii
JOIN entry e ON e.invoiceInFk = ii.id
JOIN duaEntry de ON de.entryFk = e.id
JOIN dua d ON d.id = de.duaFk
SET ii.isBooked = TRUE,
ii.booked = IFNULL(ii.booked,d.booked),
ii.operated = IFNULL(ii.operated,d.operated),
ii.issued = IFNULL(ii.issued,d.issued),
ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried),
e.isConfirmed = TRUE
WHERE d.id = vDuaFk;
SELECT IFNULL(ASIEN,0) INTO vASIEN
FROM dua
WHERE id = vDuaFk;
FETCH rs INTO vInvoiceFk;
WHILE NOT done DO
CALL invoiceInBookingMain(vInvoiceFk);
IF vCounter > 0 OR vASIEN > 0 THEN
UPDATE XDiario x
JOIN config c ON c.ASIEN = x.ASIEN
SET x.ASIEN = vASIEN;
ELSE
SELECT ASIEN INTO vASIEN FROM config;
END IF;
SET vCounter = vCounter + 1;
FETCH rs INTO vInvoiceFk;
END WHILE;
CLOSE rs;
UPDATE dua
SET ASIEN = vASIEN
WHERE id = vDuaFk;
END$$
DELIMITER ;

View File

@ -1,17 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `getItemVisibleAvailable`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `getItemVisibleAvailable`(
vItem INT,
vDate DATE,
vWarehouse TINYINT,
vRefresh BOOL)
BEGIN
-- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20
CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh);
END$$
DELIMITER ;

View File

@ -1,17 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `itemGetVisibleAvailable`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `itemGetVisibleAvailable`(
vItem INT,
vDate DATE,
vWarehouse TINYINT,
vRefresh BOOL)
BEGIN
-- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20
CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh);
END$$
DELIMITER ;

View File

@ -1,71 +0,0 @@
USE `vn`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisibleAvailable`(
vItem INT,
vDate DATE,
vWarehouse TINYINT,
vRefresh BOOL)
BEGIN
DECLARE vVisibleCalc INT;
DECLARE vAvailableCalc INT;
DECLARE vVisibleAltillo INT;
CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/ , vWarehouse, vDate);
CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse);
SELECT visible INTO vVisibleAltillo
FROM vn.itemShelvingStock
WHERE itemFk = vItem
AND warehouseFk = vWarehouse;
IF vRefresh THEN
DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item;
CREATE TEMPORARY TABLE vn2008.tmp_item
(PRIMARY KEY (item_id))
ENGINE = MEMORY
SELECT vItem item_id, 0 stock, 0 visible;
SELECT i.id, i.longName, i.box, i.typeFk,
i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8,
ip.code, ip.reserve,
vi.visible - IFNULL(vVisibleAltillo,0) AS visible,
av.available
FROM vn.item i
LEFT JOIN vn.itemPlacement ip
ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse
LEFT JOIN vn2008.tmp_item v
ON v.item_id = i.id
LEFT JOIN cache.available av
ON av.calc_id = vAvailableCalc AND av.item_id = i.id
LEFT JOIN cache.visible vi
ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id
LEFT JOIN cache.stock st
ON st.warehouse_id = vWarehouse AND st.item_id = i.id
WHERE (vItem IS NULL OR i.id = vItem);
ELSE
SELECT i.id, i.longName, i.box, i.typeFk,
i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8,
ip.code, ip.reserve,
v.visible - IFNULL(vVisibleAltillo,0) AS visible,
av.available
FROM vn.item i
LEFT JOIN vn.itemPlacement ip
ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse
LEFT JOIN cache.visible v
ON v.item_id = i.id AND v.calc_id = vVisibleCalc
LEFT JOIN cache.available av
ON av.item_id = i.id AND av.calc_id = vAvailableCalc
WHERE (vItem IS NULL OR i.id = vItem);
END IF;
END$$
DELIMITER ;
;

View File

@ -1,7 +0,0 @@
USE `vn`;
ALTER TABLE `vn`.`payMethod`
ADD COLUMN `code` VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL AFTER `id`;
UPDATE `vn`.`payMethod` SET `code` = 'bankDraft' WHERE (`id` = '4');
UPDATE `vn`.`payMethod` SET `code` = 'card' WHERE (`id` = '5');

View File

@ -1,41 +0,0 @@
DROP procedure IF EXISTS `vn`.`rangeDateInfo`;
DELIMITER $$
CREATE PROCEDURE `vn`.`rangeDateInfo` (vStarted DATE, vEnded DATE)
BEGIN
/**
* Crea una tabla temporal con las fechas
* desde una fecha inicial a una final
* @param vStarted fecha inicial
* @param vEnded fecha final
*/
DECLARE vDated DATE DEFAULT vStarted;
DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate;
CREATE TEMPORARY TABLE tmp.rangeDate(
`dated` DATE,
`period` INT,
`month` INT,
`year` INT,
`day` INT,
`week` INT,
`yearMonth` INT
)
ENGINE = MEMORY;
WHILE vDated <= vEnded DO
INSERT INTO tmp.rangeDate
SET `dated` = vDated,
`period` = YEAR(vDated) * 100 + WEEK(vDated, 1),
`month` = MONTH(vDated),
`year` = YEAR(vDated),
`day` = DAY(vDated),
`week` = WEEK(vDated, 1),
`yearMonth` = YEAR(vDated) * 100 + MONTH(vDated);
SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY);
END WHILE;
END$$
DELIMITER ;

View File

@ -1,8 +0,0 @@
USE `vn`;
UPDATE `vn`.`sample` SET `description` = 'Bienvenida como nuevo cliente' WHERE (`id` = '12');
UPDATE `vn`.`sample` SET `description` = 'Instalación y configuración de impresora de coronas' WHERE (`id` = '13');
UPDATE `vn`.`sample` SET `description` = 'Solicitud de domiciliación bancaria' WHERE (`id` = '14');
UPDATE `vn`.`sample` SET `description` = 'Aviso inicial por saldo deudor' WHERE (`id` = '15');
UPDATE `vn`.`sample` SET `description` = 'Aviso reiterado por saldo deudor' WHERE (`id` = '16');
UPDATE `vn`.`sample` SET `isVisible` = '0' WHERE (`id` = '17');

View File

@ -1,116 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `ticketClosure`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosure`()
BEGIN
/**
* Realiza el cierre de todos los
* tickets de la table ticketClosure.
*/
DECLARE vDone BOOL;
DECLARE vClientFk INT;
DECLARE vTicketFk INT;
DECLARE vIsTaxDataChecked BOOL;
DECLARE vCompanyFk INT;
DECLARE vShipped DATE;
DECLARE vPriority INT DEFAULT 1;
DECLARE vReportDeliveryNote INT DEFAULT 1;
DECLARE vNewInvoiceId INT;
DECLARE vHasDailyInvoice BOOL;
DECLARE vWithPackage BOOL;
DECLARE cur CURSOR FOR
SELECT ticketFk FROM tmp.ticketClosure;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
RESIGNAL;
END;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2;
CREATE TEMPORARY TABLE tmp.ticketClosure2
SELECT ticketFk FROM tmp.ticketClosure;
INSERT INTO tmp.ticketClosure
SELECT id FROM stowaway s
JOIN tmp.ticketClosure2 tc ON s.shipFk = tc.ticketFk;
OPEN cur;
proc: LOOP
SET vDone = FALSE;
FETCH cur INTO vTicketFk;
IF vDone THEN
LEAVE proc;
END IF;
-- ticketClosure start
SELECT
c.id,
c.isTaxDataChecked,
t.companyFk,
t.shipped,
co.hasDailyInvoice,
w.isManaged
INTO vClientFk,
vIsTaxDataChecked,
vCompanyFk,
vShipped,
vHasDailyInvoice,
vWithPackage
FROM ticket t
JOIN `client` c ON c.id = t.clientFk
JOIN province p ON p.id = c.provinceFk
JOIN country co ON co.id = p.countryFk
JOIN warehouse w ON w.id = t.warehouseFk
WHERE t.id = vTicketFk;
INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity)
(SELECT vTicketFk, p.id, COUNT(*)
FROM expedition e
JOIN packaging p ON p.itemFk = e.itemFk
WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable
AND vWithPackage
GROUP BY p.itemFk);
-- No retornables o no catalogados
INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed)
(SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1
FROM expedition e
JOIN item i ON i.id = e.itemFk
LEFT JOIN packaging p ON p.itemFk = i.id
WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0
AND getSpecialPrice(e.itemFk, vClientFk) > 0
GROUP BY e.itemFk);
IF(vHasDailyInvoice) THEN
-- Facturacion rapida
CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL);
-- Facturar si está contabilizado
IF vIsTaxDataChecked THEN
CALL invoiceOut_newFromClient(
vClientFk,
(SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')),
vShipped,
vCompanyFk,
NULL,
vNewInvoiceId);
END IF;
ELSE
-- Albaran_print
CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL);
END IF;
-- ticketClosure end
END LOOP;
CLOSE cur;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2;
END$$
DELIMITER ;

View File

@ -1,54 +0,0 @@
ALTER TABLE `vn`.`ticketRequest`
DROP FOREIGN KEY `fgnAtender`;
ALTER TABLE `vn`.`ticketRequest`
CHANGE COLUMN `atenderFk` `attenderFk` INT(11) NULL DEFAULT NULL ;
ALTER TABLE `vn`.`ticketRequest`
ADD CONSTRAINT `fgnAtender`
FOREIGN KEY (`attenderFk`)
REFERENCES `vn`.`worker` (`id`)
ON UPDATE CASCADE;
DROP TRIGGER IF EXISTS `vn`.`ticketRequest_beforeInsert`;
DELIMITER $$
CREATE DEFINER=`root`@`%` TRIGGER `vn`.`ticketRequest_beforeInsert` BEFORE INSERT ON `ticketRequest` FOR EACH ROW
BEGIN
IF NEW.ticketFk IS NULL THEN
SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk);
END IF;
IF NEW.requesterFk IS NULL THEN
SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode);
END IF;
IF NEW.attenderFk IS NULL THEN
SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode);
END IF;
END$$
DELIMITER ;
DROP TRIGGER IF EXISTS `vn`.`ticketRequest_beforeUpdate`;
DELIMITER $$
CREATE DEFINER=`root`@`%` TRIGGER `vn`.`ticketRequest_beforeUpdate` BEFORE UPDATE ON `ticketRequest` FOR EACH ROW
BEGIN
IF NEW.saleFk <> OLD.saleFk THEN
SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk);
END IF;
IF NEW.salesPersonCode <> OLD.salesPersonCode THEN
SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode);
END IF;
IF NEW.buyerCode <> OLD.buyerCode THEN
SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode);
END IF;
END$$
DELIMITER ;

View File

@ -1,77 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `ticket_recalcComponents`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT )
proc: BEGIN
/**
* Este procedimiento trata de "rebionizar" un ticket,
* eliminando los componentes existentes e insertandolos de nuevo
*
* @param vTicketFk Id del ticket
* @return tmp.buyUltimate
*/
DECLARE vShipped DATE;
DECLARE vWarehouseFk SMALLINT;
DECLARE vAgencyModeFk INT;
DECLARE vAddressFk INT;
DECLARE vLanded DATE;
DECLARE vIsTicketEditable BOOLEAN;
DECLARE vZoneFk INTEGER;
SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk
INTO vIsTicketEditable, vZoneFk
FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket
WHERE id = vTicketFk;
SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed
INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded
FROM ticket
WHERE id = vTicketFk;
CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk);
CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot
SELECT vWarehouseFk warehouseFk, NULL available,
s.itemFk, bu.buyFk
FROM sale s
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
WHERE s.ticketFk = vTicketFk
GROUP BY s.itemFk;
CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);
DROP TEMPORARY TABLE IF EXISTS tmp.sale;
CREATE TEMPORARY TABLE tmp.sale
(PRIMARY KEY (saleFk)) ENGINE = MEMORY
SELECT id saleFk, vWarehouseFk warehouseFk
FROM sale s
WHERE s.ticketFk = vTicketFk;
CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios
IF vLanded IS NULL THEN
CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk);
UPDATE vn2008.Tickets t
SET t.landing = (SELECT landed FROM tmp.zoneGetLanded)
WHERE Id_Ticket = vTicketFk;
DROP TEMPORARY TABLE tmp.zoneGetLanded;
END IF;
DROP TEMPORARY TABLE tmp.buyUltimate;
DROP TEMPORARY TABLE tmp.ticketComponentPrice;
DROP TEMPORARY TABLE tmp.ticketComponent;
DROP TEMPORARY TABLE tmp.sale;
END$$
DELIMITER ;

View File

@ -1,77 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `ticket_recalcComponentsForcePrice`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN )
proc: BEGIN
/**
* Este procedimiento trata de "rebionizar" un ticket,
* eliminando los componentes existentes e insertandolos de nuevo
*
* @param vTicketFk Id del ticket
* @return tmp.buyUltimate
*/
DECLARE vShipped DATE;
DECLARE vWarehouseFk SMALLINT;
DECLARE vAgencyModeFk INT;
DECLARE vAddressFk INT;
DECLARE vLanded DATE;
DECLARE vZoneFk INTEGER;
IF vIsTicketEditable IS NULL THEN
SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk
INTO vIsTicketEditable, vZoneFk
FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket
WHERE id = vTicketFk;
END IF;
SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed
INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded
FROM ticket
WHERE id = vTicketFk;
CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk);
CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot
SELECT vWarehouseFk warehouseFk, NULL available,
s.itemFk, bu.buyFk
FROM sale s
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
WHERE s.ticketFk = vTicketFk
GROUP BY s.itemFk;
CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);
DROP TEMPORARY TABLE IF EXISTS tmp.sale;
CREATE TEMPORARY TABLE tmp.sale
(PRIMARY KEY (saleFk)) ENGINE = MEMORY
SELECT id saleFk, vWarehouseFk warehouseFk
FROM sale s
WHERE s.ticketFk = vTicketFk;
CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios
IF vLanded IS NULL THEN
CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk);
UPDATE vn2008.Tickets t
SET t.landing = (SELECT landed FROM tmp.zoneGetLanded)
WHERE Id_Ticket = vTicketFk;
DROP TEMPORARY TABLE tmp.zoneGetLanded;
END IF;
DROP TEMPORARY TABLE tmp.buyUltimate;
DROP TEMPORARY TABLE tmp.ticketComponentPrice;
DROP TEMPORARY TABLE tmp.ticketComponent;
DROP TEMPORARY TABLE tmp.sale;
END$$
DELIMITER ;

View File

@ -1,73 +0,0 @@
DROP function IF EXISTS `vn`.`workerTimeControl_add`;
DELIMITER $$
CREATE DEFINER=`root`@`%` FUNCTION `vn`.`workerTimeControl_add`( vUserFk INT, vWarehouseFk INT, vTimed DATETIME, vIsManual BOOL) RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE vDirection VARCHAR(6);
DECLARE vLastIn DATETIME;
DECLARE vDayStayMax INT;
DECLARE vHasDirectionOut INT;
DECLARE vLastInsertedId INT;
SELECT dayStayMax INTO vDayStayMax
FROM workerTimeControlParams;
SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection;
IF vDirection = 'out' THEN
SELECT MAX(timed) INTO vLastIn
FROM workerTimeControl
WHERE userFk = vUserFk
AND direction = 'in'
AND timed < vTimed;
UPDATE workerTimeControl wtc
SET wtc.direction = 'middle'
WHERE userFk = vUserFk
AND direction = 'out'
AND timed BETWEEN vLastIn AND vTimed;
ELSE IF vDirection = 'in' THEN
SELECT COUNT(*) INTO vHasDirectionOut
FROM workerTimeControl wtc
WHERE userFk = vUserFk
AND direction = 'out'
AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
UPDATE workerTimeControl wtc
SET wtc.direction = IF (vHasDirectionOut,'middle','out')
WHERE userFk = vUserFk
AND direction = 'in'
AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
END IF;
END IF;
INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual)
VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual);
SET vLastInsertedId = LAST_INSERT_ID();
CALL workerTimeControlSOWP(vUserFk, vTimed);
RETURN vLastInsertedId;
END$$
DELIMITER ;
DROP procedure IF EXISTS `vn`.`workerTimeControl_add`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL)
BEGIN
SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual);
END$$
DELIMITER ;

View File

@ -1,53 +0,0 @@
CREATE
OR REPLACE ALGORITHM = UNDEFINED
DEFINER = `root`@`%`
SQL SECURITY DEFINER
VIEW `vn2008`.`Ordenes` AS
SELECT
`tr`.`id` AS `Id_ORDEN`,
`tr`.`description` AS `ORDEN`,
`tr`.`requesterFk` AS `requesterFk`,
`tr`.`attenderFk` AS `attenderFk`,
`tr`.`quantity` AS `CANTIDAD`,
`tr`.`itemFk` AS `Id_ARTICLE`,
`tr`.`price` AS `PRECIOMAX`,
`tr`.`isOk` AS `isOk`,
`tr`.`saleFk` AS `Id_Movimiento`,
`tr`.`ticketFk` AS `ticketFk`,
`tr`.`response` AS `COMENTARIO`,
`tr`.`created` AS `odbc_date`,
`tr`.`ordered` AS `datORDEN`,
`tr`.`shipped` AS `datTICKET`,
`tr`.`salesPersonCode` AS `CodVENDEDOR`,
`tr`.`buyerCode` AS `CodCOMPRADOR`,
`tr`.`price__` AS `PREU`,
`tr`.`clientFk` AS `Id_CLIENTE`,
`tr`.`ok__` AS `OK`,
`tr`.`total` AS `TOTAL`,
`tr`.`buyed` AS `datCOMPRA`,
`tr`.`ko__` AS `KO`
FROM
`vn`.`ticketRequest` `tr`;
CREATE
OR REPLACE ALGORITHM = UNDEFINED
DEFINER = `root`@`%`
SQL SECURITY DEFINER
VIEW `vn`.`ticketRequest__` AS
SELECT
`t`.`Id_ORDEN` AS `id`,
`t`.`ORDEN` AS `description`,
`t`.`requesterFk` AS `requesterFk`,
`t`.`attenderFk` AS `attenderFk`,
`t`.`CANTIDAD` AS `quantity`,
`t`.`Id_ARTICLE` AS `itemFk`,
`t`.`PRECIOMAX` AS `price`,
`t`.`isOk` AS `isOk`,
`t`.`Id_Movimiento` AS `saleFk`,
`t`.`ticketFk` AS `ticketFk`,
`t`.`COMENTARIO` AS `response`,
`t`.`odbc_date` AS `created`
FROM
`vn2008`.`Ordenes` `t`;

View File

@ -1,92 +0,0 @@
DROP function IF EXISTS `vn`.`bionicCalcReverse`;
DELIMITER $$
CREATE DEFINER=`root`@`%` FUNCTION `vn`.`bionicCalcReverse`(vWarehouse INT,
vMargin DECIMAL(10,3),
vRetailedPrice DECIMAL(10,3),
vM3 DECIMAL(10,3),
vAddress INT,
vAgencyMode INT) RETURNS decimal(10,3)
DETERMINISTIC
BEGIN
DECLARE vGeneralInflationCoeficient INT;
DECLARE vVerdnaturaVolumeBox BIGINT;
DECLARE vClientFk INT;
DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection';
DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana';
DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery';
DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin';
DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue';
DECLARE vComponentCostValue DECIMAL(10,2);
DECLARE vItem INT DEFAULT 98;
DECLARE vItemCarryBox INT;
SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox
INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox
FROM bionicConfig;
SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress;
-- Creamos la tabla tmp.bionicComponent
DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent;
CREATE TEMPORARY TABLE tmp.bionicComponent(
`warehouseFk` smallint(5) unsigned NOT NULL,
`itemFk` int(11) NOT NULL,
`componentFk` int(10) unsigned NOT NULL,
`value` decimal(10,4) NOT NULL,
UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH,
KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- Margin
INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
SELECT vWarehouse, vItem, id, vMargin
FROM component
WHERE code = vComponentMargin;
-- Recobro
INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3)
FROM bi.claims_ratio cr
JOIN component c ON c.code = vComponentRecovery
WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009;
-- Componente de maná automático, en función del maná acumulado por el comercial.
INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3)
FROM client c
JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador
JOIN component co ON co.code = vComponentMana
WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1;
-- Reparto
INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient
* ROUND(
vM3
* az.price
* az.inflation
/ vVerdnaturaVolumeBox, 4
)
FROM agencyMode ag
JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode
JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk
AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk
JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode
AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse
JOIN component co ON co.code = vComponentPort;
-- Coste
SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue
FROM tmp.bionicComponent;
INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
SELECT vWarehouse, vItem, id,vComponentCostValue
FROM component
WHERE code = vComponentCost;
RETURN vComponentCostValue;
END$$
DELIMITER ;

View File

@ -1,96 +0,0 @@
DROP procedure IF EXISTS `vn`.`timeBusiness_calculate`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
/**
* Horas que debe trabajar un empleado según contrato y día.
* @param vDatedFrom workerTimeControl
* @param vDatedTo workerTimeControl
* @table tmp.user(userFk)
* @return tmp.timeBusinessCalculate
*/
DECLARE vHoursFullTime INT DEFAULT 40;
DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate;
DROP TEMPORARY TABLE IF EXISTS tmp.businessFullTime;
CALL rangeDateInfo(vDatedFrom, vDatedTo);
CREATE TEMPORARY TABLE tmp.timeBusinessCalculate
SELECT dated,
businessFk,
userFk,
departmentFk,
hourStart,
hourEnd,
timeWorkSeconds,
SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal,
timeWorkSeconds / 3600 timeWorkDecimal,
timeWorkSeconds timeBusinessSeconds,
SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal,
timeWorkSeconds / 3600 timeBusinessDecimal,
type,
permissionrate,
hoursWeek
FROM(SELECT rd.dated,
b.business_id businessFk,
w.userFk,
bl.department_id departmentFk,
IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,2) ORDER BY j.start ASC SEPARATOR '-')) hourStart ,
IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,2) ORDER BY j.end ASC SEPARATOR '-')) hourEnd,
IF(cl.hours_week = vHoursFullTime, 0, IFNULL(SUM(TIME_TO_SEC(j.end)) - SUM(TIME_TO_SEC(j.start)),0)) timeWorkSeconds,
cs.type,
cs.permissionRate,
cl.hours_week hoursWeek
FROM tmp.rangeDate rd
LEFT JOIN postgresql.business b ON rd.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo )
LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id
LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id
LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id
JOIN tmp.`user` u ON u.userFK = w.userFK
JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id
LEFT JOIN postgresql.business_labour_payroll AS bp ON bl.business_id = bp.business_id
LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id
LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id
LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id
LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(rd.dated)+1
LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = rd.dated
LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id
WHERE rd.dated BETWEEN vDatedFrom AND vDatedTo
GROUP BY w.userFk,dated
)sub;
UPDATE tmp.timeBusinessCalculate t
SET t.timeWorkSeconds = vHoursFullTime / 5 * 3600,
t.timeWorkSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600),
t.timeWorkDecimal = vHoursFullTime / 5,
t.timeBusinessSeconds = vHoursFullTime / 5 * 3600,
t.timeBusinessSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600),
t.timeBusinessDecimal = vHoursFullTime / 5
WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND hoursWeek = vHoursFullTime ;
UPDATE tmp.timeBusinessCalculate t
SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate) ,
t.timeWorkSexagesimal = SEC_TO_TIME(t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate)),
t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionrate)
WHERE permissionrate <> 0;
UPDATE tmp.timeBusinessCalculate t
JOIN postgresql.calendar_labour cl ON cl.day = t.dated
JOIN postgresql.business_labour bl ON bl.business_id = t.businessFk AND bl.workcenter_id = cl.workcenter_id
SET t.timeWorkSeconds = 0,
t.timeWorkSexagesimal = 0,
t.timeWorkDecimal = 0,
t.permissionrate = 1,
t.type = 'Festivo'
WHERE t.type IS NULL;
DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate;
END$$
DELIMITER ;

View File

@ -1,58 +0,0 @@
DROP TRIGGER IF EXISTS `vn`.`entry_beforeUpdate`;
DELIMITER $$
CREATE DEFINER=`root`@`%` TRIGGER `vn`.`entry_beforeUpdate`
BEFORE UPDATE ON `entry`
FOR EACH ROW
BEGIN
DECLARE vIsVirtual BOOL;
DECLARE vPrintedCount INT;
DECLARE vHasDistinctWarehouses BOOL;
IF !(NEW.travelFk <=> OLD.travelFk) THEN
SELECT COUNT(*) > 0 INTO vIsVirtual
FROM entryVirtual WHERE entryFk = NEW.id;
SELECT !(o.warehouseInFk <=> n.warehouseInFk)
OR !(o.warehouseOutFk <=> n.warehouseOutFk)
INTO vHasDistinctWarehouses
FROM travel o, travel n
WHERE o.id = OLD.travelFk
AND n.id = NEW.travelFk;
IF vIsVirtual AND vHasDistinctWarehouses THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses';
END IF;
IF NEW.travelFk IS NULL THEN
SELECT COUNT(*) INTO vPrintedCount
FROM buy
WHERE entryFk = OLD.id
AND printedStickers > 0;
IF vPrintedCount > 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'An entry that contains lines with printed labels cannot be deleted';
END IF;
END IF;
END IF;
IF !(NEW.supplierFk <=> OLD.supplierFk) THEN
SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk);
END IF;
IF !(NEW.travelFk <=> OLD.travelFk)
OR !(NEW.currencyFk <=> OLD.currencyFk) THEN
SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk);
END IF;
IF !(ABS(NEW.isBooked) <=> ABS(OLD.isBooked)) THEN
INSERT INTO entryLog SET
action = 'update',
description = 'Cambia a Contabilizada',
userFk = myWorker_getId(),
originFk = NEW.id;
END IF;
END$$
DELIMITER ;

View File

@ -1,33 +0,0 @@
DROP TRIGGER IF EXISTS `vn`.`expedition_beforeInsert`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` TRIGGER `vn`.`expedition_beforeInsert`
BEFORE INSERT ON `expedition` FOR EACH ROW
BEGIN
DECLARE intcounter INT;
DECLARE vShipFk INT;
IF NEW.isBox > 0 THEN
UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk;
SELECT IFNULL(MAX(counter),0) +1 INTO intcounter
FROM expedition e
INNER JOIN ticket t1 ON e.ticketFk = t1.id
LEFT JOIN ticketState ts ON ts.ticket = t1.id
INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped)
AND t1.warehouseFk = t2.warehouseFk
WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk
AND t1.agencyModeFk = t2.agencyModeFk;
SET NEW.`counter` = intcounter;
END IF;
SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk;
IF vShipFk THEN
CALL stowaway_unboarding(vShipFk, NEW.ticketFk);
END IF;
END$$
DELIMITER ;

View File

@ -1,31 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `vn`.`stowawayUnBoarding`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `stowaway_unboarding`(vShipFk INT, vStowawayFk INT)
BEGIN
DECLARE vWorker VARCHAR(255);
DELETE FROM stowaway
WHERE shipFk = vShipFk AND id = vStowawayFk;
DELETE tt FROM ticketTracking tt
JOIN state s ON s.id = tt.stateFk
WHERE code = 'BOARDING' AND ticketFk = vShipFk;
DELETE FROM sale
WHERE ticketFk = vShipFk
AND itemFk = 98
AND concept = CONCAT('POLIZÓN! ',vStowawayFk);
SELECT u.`name` INTO vWorker
FROM account.user u JOIN worker w ON w.userFk = u.id
WHERE w.id = client_getSalesPersonByTicket(vStowawayFk);
SELECT messageSend(vWorker,CONCAT('El ticket: ', vStowawayFk, ' ha dejado de ser un polizón')) INTO @a;
END$$
DELIMITER ;
;

View File

@ -1,120 +0,0 @@
DROP procedure IF EXISTS `hedera`.`tpvTransaction_confirm`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `hedera`.`tpvTransaction_confirm`(
vAmount INT
,vOrder INT
,vMerchant INT
,vCurrency INT
,vResponse INT
,vErrorCode VARCHAR(10)
)
BEGIN
/**
* Confirma una transacción previamente iniciada, reescribiendo
* sus datos por los confirmados por el banco (solo si estos difieren).
* Genera el recibo y su correspondiente entrada en caja.
*
* @param vAmount Cantidad confirmada
* @param vOrder Identificador de transacción
* @param vMerchant Identificador de comercio
* @param vCurrency Identificador de moneda
* @param vResponse Identificador de respuesta del banco
* @param vErrorCode Código de error del banco, si lo hubiera
*/
DECLARE vReceipt INT;
DECLARE vStatus VARCHAR(10);
DECLARE vCustomer INT;
DECLARE vBank INT;
DECLARE vCompany INT;
DECLARE vEmployee INT;
DECLARE vIsDuplicated BOOLEAN;
DECLARE vDate DATE;
DECLARE vConcept VARCHAR(25) DEFAULT 'Cobro Web';
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
SELECT COUNT(*) > 0 INTO vIsDuplicated
FROM tpvTransaction
WHERE id = vOrder AND response IS NOT NULL
FOR UPDATE;
IF vIsDuplicated
THEN
CALL util.throw ('TRANSACTION_DUPLICATED');
END IF;
IF vResponse BETWEEN 0 AND 99
THEN
SELECT
t.clientFk
,m.bankFk
,m.companyFk
,c.employeeFk
,DATE(t.created)
INTO
vCustomer
,vBank
,vCompany
,vEmployee
,vDate
FROM tpvMerchant m
JOIN tpvConfig c
LEFT JOIN tpvTransaction t ON t.id = vOrder
WHERE m.id = vMerchant;
INSERT INTO vn.receipt
SET
amountPaid = vAmount / 100
,payed = vDate
,workerFk = vEmployee
,bankFk = vBank
,clientFk = vCustomer
,companyFk = vCompany
,invoiceFk = vConcept
,isConciliate = TRUE;
SET vReceipt = LAST_INSERT_ID();
SET vStatus = 'ok';
-- Código redundante
DO vn.till_new
(
vCustomer
,vBank
,vAmount / 100
,vConcept
,vDate
,'A'
,TRUE
,vCustomer
,vCompany
,vEmployee
);
ELSE
SET vReceipt = NULL;
SET vStatus = 'ko';
END IF;
UPDATE tpvTransaction
SET
merchantFk = vMerchant
,receiptFk = vReceipt
,amount = vAmount
,response = vResponse
,errorCode = vErrorCode
,status = vStatus
WHERE id = vOrder;
COMMIT;
END$$
DELIMITER ;

View File

@ -1,86 +0,0 @@
DROP procedure IF EXISTS `hedera`.`tpvTransaction_undo`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `hedera`.`tpvTransaction_undo`(vSelf INT)
BEGIN
DECLARE vCustomer INT;
DECLARE vAmount DOUBLE;
DECLARE vReceipt INT;
DECLARE vDate DATE;
DECLARE vBank INT;
DECLARE vAccount VARCHAR(12);
DECLARE vSubaccount VARCHAR(12);
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
SELECT
t.clientFk
,t.amount / 100
,t.receiptFk
,DATE(t.created)
,m.bankFk
INTO
vCustomer
,vAmount
,vReceipt
,vDate
,vBank
FROM tpvTransaction t
JOIN tpvMerchant m ON m.id = t.merchantFk
JOIN tpvConfig c
WHERE t.id = vSelf
FOR UPDATE;
-- Elimina el recibo
DELETE FROM vn.receipt
WHERE id = vReceipt LIMIT 1;
-- Elimina la entrada de cajas
DELETE FROM vn.till
WHERE bankFk = vBank
AND DATE(dated) = vDate
AND `in` = vAmount
LIMIT 1;
-- Elimina los asientos contables
SELECT accountingAccount INTO vSubaccount
FROM vn.`client` WHERE id = vCustomer;
SELECT account INTO vAccount
FROM vn.bank WHERE id = vBank;
DELETE FROM vn.XDiario
WHERE SUBCTA = vSubaccount
AND CONTRA = vAccount
AND DATE(FECHA) = vDate
AND EUROHABER = vAmount
LIMIT 1;
DELETE FROM vn.XDiario
WHERE CONTRA = vSubaccount
AND SUBCTA = vAccount
AND DATE(FECHA) = vDate
AND EURODEBE = vAmount
LIMIT 1;
-- Actualiza la transaccion
UPDATE tpvTransaction
SET response = NULL, status = 'started'
WHERE id = vSelf;
COMMIT;
END$$
DELIMITER ;

View File

@ -1,9 +1,7 @@
USE `vn`; DROP procedure IF EXISTS `vn`.`catalog_componentCalculate`;
DROP procedure IF EXISTS `catalog_componentCalculate`;
DELIMITER $$ DELIMITER $$
USE `vn`$$ CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`catalog_componentCalculate`(
CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`(
vZoneFk INT, vZoneFk INT,
vAddressFk INT, vAddressFk INT,
vShipped DATE) vShipped DATE)
@ -19,7 +17,6 @@ proc: BEGIN
* packing, grouping, groupingMode, buyFk, typeFk) * packing, grouping, groupingMode, buyFk, typeFk)
* @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price)
*/ */
DECLARE vClientFk INT; DECLARE vClientFk INT;
DECLARE vGeneralInflationCoefficient INT DEFAULT 1; DECLARE vGeneralInflationCoefficient INT DEFAULT 1;
DECLARE vMinimumDensityWeight INT DEFAULT 167; DECLARE vMinimumDensityWeight INT DEFAULT 167;
@ -112,29 +109,29 @@ proc: BEGIN
GROUP BY tc.itemFk, warehouseFk; GROUP BY tc.itemFk, warehouseFk;
INSERT INTO tmp.ticketComponent INSERT INTO tmp.ticketComponent
SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.priceIncreasing, 0.25), 3)
FROM tmp.ticketComponentBase tcb FROM tmp.ticketComponentBase tcb
JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk JOIN claimRatio cr ON cr.clientFk = vClientFk
WHERE cr.recobro > 0.009; WHERE cr.priceIncreasing > 0.009;
INSERT INTO tmp.ticketComponent INSERT INTO tmp.ticketComponent
SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto
FROM tmp.ticketComponentBase tcb FROM tmp.ticketComponentBase tcb
JOIN `client` c on c.id = vClientFk JOIN `client` c on c.id = vClientFk
JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador JOIN workerMana wm ON c.salesPersonFk = wm.workerFk
WHERE ms.prices_modifier_activated WHERE wm.isPricesModifierActivated
HAVING manaAuto <> 0; HAVING manaAuto <> 0;
INSERT INTO tmp.ticketComponent INSERT INTO tmp.ticketComponent
SELECT tcb.warehouseFk, SELECT tcb.warehouseFk,
tcb.itemFk, tcb.itemFk,
cr.id, c.id,
GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) GREATEST(IFNULL(ROUND(tcb.base * c.tax, 4), 0), tcc.minPrice - tcc.rate3)
FROM tmp.ticketComponentBase tcb FROM tmp.ticketComponentBase tcb
JOIN componentRate cr JOIN component c
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 specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; WHERE c.id = vDiscountLastItemComponent AND c.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL;
INSERT INTO tmp.ticketComponent INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3
@ -150,7 +147,7 @@ proc: BEGIN
vGeneralInflationCoefficient vGeneralInflationCoefficient
* ROUND(( * ROUND((
i.compression i.compression
* r.cm3 * ic.cm3
* IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1)
* IFNULL((z.price - z.bonus) * IFNULL((z.price - z.bonus)
* 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4
@ -159,8 +156,8 @@ proc: BEGIN
JOIN item i ON i.id = tcc.itemFk JOIN item i ON i.id = tcc.itemFk
JOIN zone z ON z.id = vZoneFk JOIN zone z ON z.id = vZoneFk
JOIN agencyMode am ON am.id = z.agencyModeFk JOIN agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk
AND r.Id_Article = tcc.itemFk AND ic.itemFk = tcc.itemFk
HAVING cost <> 0; HAVING cost <> 0;
IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN
@ -181,9 +178,9 @@ proc: BEGIN
vSpecialPriceComponent, vSpecialPriceComponent,
sp.value - SUM(tcc.cost) sumCost sp.value - SUM(tcc.cost) sumCost
FROM tmp.ticketComponentCopy tcc FROM tmp.ticketComponentCopy tcc
JOIN componentRate cr ON cr.id = tcc.componentFk JOIN component c ON c.id = tcc.componentFk
JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk
WHERE cr.classRate IS NULL WHERE c.classRate IS NULL
GROUP BY tcc.itemFk, tcc.warehouseFk GROUP BY tcc.itemFk, tcc.warehouseFk
HAVING ABS(sumCost) > 0.001; HAVING ABS(sumCost) > 0.001;
@ -191,10 +188,10 @@ proc: BEGIN
CREATE TEMPORARY TABLE tmp.ticketComponentSum CREATE TEMPORARY TABLE tmp.ticketComponentSum
(INDEX (itemFk, warehouseFk)) (INDEX (itemFk, warehouseFk))
ENGINE = MEMORY ENGINE = MEMORY
SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, c.classRate
FROM tmp.ticketComponent tc FROM tmp.ticketComponent tc
JOIN componentRate cr ON cr.id = tc.componentFk JOIN component c ON c.id = tc.componentFk
GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; GROUP BY tc.itemFk, tc.warehouseFk, c.classRate;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate;
CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY
@ -254,6 +251,4 @@ proc: BEGIN
tmp.ticketComponentRate, tmp.ticketComponentRate,
tmp.ticketComponentCopy; tmp.ticketComponentCopy;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -0,0 +1,5 @@
ALTER TABLE `vn`.`chatConfig`
ADD COLUMN `host` VARCHAR(255) NOT NULL AFTER `id`,
CHANGE COLUMN `uri` `api` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL ;
UPDATE `vn`.`chatConfig` SET `host` = 'https://chat.verdnatura.es' WHERE (`id` = '1');

View File

@ -0,0 +1,6 @@
CREATE TABLE `vn`.`greugeConfig` (
`id` INT NOT NULL AUTO_INCREMENT,
`freightPickUpPrice` DECIMAL(10,2) NOT NULL,
PRIMARY KEY (`id`));
INSERT IGNORE INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11');

View File

@ -0,0 +1,70 @@
DROP procedure IF EXISTS `vn`.`manaSpellersRequery`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`manaSpellersRequery`(vWorkerFk INTEGER)
BEGIN
DECLARE vWorkerIsExcluded BOOLEAN;
DECLARE vFromDated DATE;
DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,CURDATE());
DECLARE vMana INT;
DECLARE vAutoMana INT;
DECLARE vManaBank INT;
DECLARE vManaGreugeType INT;
SELECT id INTO vMana
FROM `component` WHERE code = 'mana';
SELECT id INTO vAutoMana
FROM `component` WHERE code = 'autoMana';
SELECT id INTO vManaBank
FROM `bank` WHERE code = 'mana';
SELECT id INTO vManaGreugeType
FROM `greugeType` WHERE code = 'mana';
SELECT COUNT(*) INTO vWorkerIsExcluded
FROM workerManaExcluded
WHERE workerFk = vWorkerFk;
IF NOT vWorkerIsExcluded THEN
SELECT max(dated) INTO vFromDated
FROM clientManaCache;
REPLACE workerMana (workerFk, amount)
SELECT vWorkerFk, sum(mana) FROM
(
SELECT s.quantity * sc.value as mana
FROM ticket t
JOIN address a ON a.id = t.addressFk
JOIN client c ON c.id = a.clientFk
JOIN sale s ON s.ticketFk = t.id
JOIN saleComponent sc ON sc.saleFk = s.id
WHERE c.salesPersonFk = vWorkerFk AND sc.componentFk IN (vMana, vAutoMana)
AND t.shipped > vFromDated AND t.shipped < vToDated
UNION ALL
SELECT - r.amountPaid
FROM receipt r
JOIN client c ON c.id = r.clientFk
WHERE c.salesPersonFk = vWorkerFk AND bankFk = vManaBank
AND payed > vFromDated
UNION ALL
SELECT g.amount
FROM greuge g
JOIN client c ON c.id = g.clientFk
WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType
AND g.shipped > vFromDated and g.shipped < CURDATE()
UNION ALL
SELECT cc.mana
FROM clientManaCache cc
JOIN client c ON c.id = cc.clientFk
WHERE c.salesPersonFk = vWorkerFk AND cc.dated = vFromDated
) sub;
END IF;
END$$
DELIMITER ;

View File

@ -1,7 +1,9 @@
DROP procedure IF EXISTS `vn`.`timeControl_calculate`; USE `vn`;
DROP procedure IF EXISTS `timeControl_calculate`;
DELIMITER $$ DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN BEGIN
SET @vIsOdd := TRUE; SET @vIsOdd := TRUE;
SET @vUser := NULL; SET @vUser := NULL;
@ -27,10 +29,10 @@ BEGIN
wtc.userFk, wtc.userFk,
wtc.timed timed, wtc.timed timed,
direction direction
FROM workerTimeControl wtc FROM (SELECT * FROM workerTimeControl ORDER BY userFk, timed ASC) wtc
JOIN tmp.`user` w ON w.userFk = wtc.userFk JOIN tmp.`user` w ON w.userFk = wtc.userFk
WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo
ORDER BY userFk, timed ORDER BY userFk, timed ASC
) sub ) sub
GROUP BY userFk, dated GROUP BY userFk, dated
ORDER BY userFk, dated ORDER BY userFk, dated
@ -39,3 +41,4 @@ BEGIN
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -0,0 +1,3 @@
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Thermograph', '*', '*', 'ALLOW', 'ROLE', 'buyer');
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('TravelThermograph', '*', '*', 'ALLOW', 'ROLE', 'buyer');
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Entry', '*', '*', 'ALLOW', 'ROLE', 'buyer');

View File

@ -0,0 +1,81 @@
DROP procedure IF EXISTS `vn`.`buy_afterUpsert`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`buy_afterUpsert`(vSelf INT)
BEGIN
/**
* Triggered actions when a buy is updated or inserted.
*
* @param vSelf The buy reference
*/
DECLARE vEntryFk INT;
DECLARE vItemFk INT;
DECLARE vStickers INT;
DECLARE vPacking INT;
DECLARE vWarehouse INT;
DECLARE vWarehouseOut INT;
DECLARE vIsMerchandise BOOL;
DECLARE vIsFeedStock BOOL;
DECLARE vLanded DATE;
DECLARE vBuyerFk INT;
DECLARE vItemName VARCHAR(50);
SELECT entryFk, itemFk, stickers, packing
INTO vEntryFk, vItemFk, vStickers, vPacking
FROM buy
WHERE id = vSelf;
SELECT t.warehouseInFk, t.warehouseOutFk, t.landed
INTO vWarehouse, vWarehouseOut, vLanded
FROM entry e
JOIN travel t ON t.id = e.travelFk
WHERE e.id = vEntryFk;
SELECT k.merchandise, it.workerFk, i.longName
INTO vIsMerchandise, vBuyerFk, vItemName
FROM itemCategory k
JOIN itemType it ON it.categoryFk = k.id
JOIN item i ON i.typeFk = it.id
WHERE i.id = vItemFk;
IF vIsMerchandise THEN
REPLACE itemCost SET
itemFk = vItemFk,
warehouseFk = vWarehouse,
cm3 = buy_getUnitVolume(vSelf);
END IF;
SELECT isFeedStock INTO vIsFeedStock
FROM warehouse WHERE id = vWarehouseOut AND id <> 13;
IF vIsFeedStock THEN
INSERT IGNORE INTO producer(`name`)
SELECT es.company_name
FROM buy b
JOIN edi.ekt be ON be.id = b.ektFk
JOIN edi.supplier es ON es.supplier_id = be.pro
WHERE b.id = vSelf;
IF buy_hasNotifyPassport(vSelf, vItemFk) THEN
CALL vn.buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking);
END IF;
END IF;
-- Aviso al comprador de modificacion de entrada en Barajas
IF (SELECT isBuyerToBeEmailed FROM warehouse WHERE id = vWarehouse)
AND vLanded = CURDATE()
AND vBuyerFk != account.myUserGetId()
THEN
CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'),
CONCAT(account.myUserGetName(),'@verdnatura.es'),
CONCAT('E ',vEntryFk,' Se ha modificado item ', vItemFk, ' ',vItemName),
'Este email se ha generado automáticamente');
END IF;
END$$
DELIMITER ;

View File

@ -0,0 +1,18 @@
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clientRisk_update`(vClientId INT, vCompanyId INT, vAmount DECIMAL(10,2))
BEGIN
IF vAmount IS NOT NULL
THEN
INSERT INTO clientRisk
SET
clientFk = vClientId,
companyFk = vCompanyId,
amount = vAmount
ON DUPLICATE KEY UPDATE
amount = amount + VALUES(amount);
END IF;
END$$
DELIMITER ;

View File

@ -0,0 +1,3 @@
ALTER TABLE `vn`.`componentType`
CHANGE COLUMN `base` `isBase` TINYINT(4) NOT NULL DEFAULT '0' COMMENT 'Marca aquellas series que se utilizan para calcular el precio base de las ventas, a efectos estadisticos' ;

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