7983-testToMaster_2438 #2977

Merged
alexm merged 212 commits from 7983-testToMaster_2438 into master 2024-09-17 05:36:47 +00:00
519 changed files with 5979 additions and 17583 deletions
Showing only changes of commit 9d35cbfae4 - Show all commits

View File

@ -1,3 +1,166 @@
# Version 24.36 - 2024-08-27
### Added 🆕
- chore: refs #7524 WIP limit call by:jorgep
- feat(update-user): refs #7848 add twoFactor by:alexm
- feat: #3199 Requested changes by:guillermo
- feat: refs #3199 Added more scopes ticket_recalcByScope by:guillermo
- feat: refs #3199 Added one more scope ticket_recalcByScope by:guillermo
- feat: refs #3199 Created ticket_recalcItemTaxCountryByScope by:guillermo
- feat: refs #3199 Requested changes by:guillermo
- feat: refs #7346 add multiple feature by:jgallego
- feat: refs #7346 backTest checks new implementation by:jgallego
- feat: refs #7346 mas intuitivo by:jgallego
- feat: refs #7514 Changes to put srt log (origin/7514-srtLog) by:guillermo
- feat: refs #7524 add default limit (origin/7524-limitSelect) by:jorgep
- feat: refs #7524 add mock limit on find query by:jorgep
- feat: refs #7524 wip remote hooks by:jorgep
- feat: refs #7567 Changed time to call event by:guillermo
- feat: refs #7567 Requested changes by:guillermo
- feat: refs #7710 pr revision by:jgallego
- feat: refs #7710 test fixed (origin/7710-cloneWithTicketPackaging, 7710-cloneWithTicketPackaging) by:jgallego
- feat: refs #7712 Fix by:guillermo
- feat: refs #7712 Unify by:guillermo
- feat: refs #7712 sizeLimit (origin/7712-sizeLimit) by:guillermo
- feat: refs #7758 Add code mandateType and accountDetailType by:ivanm
- feat: refs #7758 Modify code lowerCamelCase and UNIQUE by:ivanm
- feat: refs #7758 accountDetailType fix deploy error by:ivanm
- feat: refs #7784 Changes in entry-order-pdf by:guillermo
- feat: refs #7784 Requested changes by:guillermo
- feat: refs #7799 Added Fk in vn.item.itemPackingTypeFk by:guillermo
- feat: refs #7800 Added company Fk by:guillermo
- feat: refs #7842 Added editorFk in vn.host by:guillermo
- feat: refs #7862 roadmap new fields by:ivanm
- feat: refs #7882 Added quadMindsConfig table by:guillermo
### Changed 📦
- refactor: refs #7567 Fix and improvement by:guillermo
- refactor: refs #7567 Minor change by:guillermo
- refactor: refs #7756 Fix tests by:guillermo
- refactor: refs #7798 Drop bi.Greuges_comercial_detail by:guillermo
- refactor: refs #7848 adapt to lilium by:alexm
### Fixed 🛠️
- feat: refs #7710 test fixed (origin/7710-cloneWithTicketPackaging, 7710-cloneWithTicketPackaging) by:jgallego
- feat: refs #7758 accountDetailType fix deploy error by:ivanm
- fix(salix): #7283 ItemFixedPrice duplicated (origin/7283_itemFixedPrice_duplicated) by:Javier Segarra
- fix: refs #7346 minor error (origin/7346, 7346) by:jgallego
- fix: refs #7355 remove and tests accounts (origin/7355-accountMigration2) by:carlossa
- fix: refs #7355 remove and tests accounts by:carlossa
- fix: refs #7524 default limit select by:jorgep
- fix: refs #7756 Foreign keys invoiceOut (origin/7756-fixRefFk) by:guillermo
- fix: refs #7756 id 0 by:guillermo
- fix: refs #7800 tpvMerchantEnable PRIMARY KEY (origin/7800-tpvMerchantEnable) by:guillermo
- fix: refs #7800 tpvMerchantEnable PRIMARY KEY by:guillermo
# Version 24.34 - 2024-08-20
### Added 🆕
- #6900 feat: clear empty by:jorgep
- #6900 feat: empty commit by:jorgep
- chore: refs #6900 beautify code by:jorgep
- chore: refs #6989 add config model by:jorgep
- feat workerActivity refs #6078 by:sergiodt
- feat: #6453 Refactor (origin/6453-orderConfirm) by:guillermo
- feat: #6453 Rollback always split by itemPackingType by:guillermo
- feat: deleted worker module code & redirect to Lilium by:Jon
- feat: refs #6453 Added new ticket search by:guillermo
- feat: refs #6453 Fixes by:guillermo
- feat: refs #6453 Minor changes by:guillermo
- feat: refs #6453 Requested changes by:guillermo
- feat: refs #6900 drop section by:jorgep
- feat: refs #7283 order by desc date by:jorgep
- feat: refs #7323 add locale by:jorgep
- feat: refs #7323 redirect to lilium by:jorgep
- feat: refs #7646 delete scannableCodeType by:robert
- feat: refs #7713 Created ACLLog by:guillermo
- feat: refs #7774 (origin/7774-ticket_cloneWeekly) by:robert
- feat: refs #7774 #7774 Changes ticket_cloneWeekly by:guillermo
- feat: refs #7774 ticket_cloneWeekly by:robert
### Changed 📦
- refactor: refs #6453 Major changes by:guillermo
- refactor: refs #6453 Minor changes by:guillermo
- refactor: refs #6453 order_confirmWithUser by:guillermo
- refactor: refs #7646 #7646 Deleted scannable* variables productionConfig by:guillermo
- refactor: refs #7820 Deprecated silexACL by:guillermo
### Fixed 🛠️
- #6900 fix: #6900 rectificative filter by:jorgep
- #6900 fix: empty commit by:jorgep
- fix(orders_filter): add sourceApp accepts by:alexm
- fix: refs #6130 commit lint by:pablone
- fix: refs #6453 order_confirmWithUser by:guillermo
- fix: refs #7283 sql by:jorgep
- fix: refs #7713 ACL Log by:guillermo
- test: fix claim descriptor redirect to lilium by:alexm
- test: fix ticket redirect to lilium by:alexm
- test: fix ticket sale e2e by:alexm
# Version 24.32 - 2024-08-06
### Added 🆕
- chore: refs #7197 add supplierActivityFk filter by:jorgep
- feat checkExpeditionPrintOut refs #7751 by:sergiodt
- feat(defaulter_filter): add department by:alexm
- feat: redirect to lilium page not found by:alexm
- feat: refactor buyUltimate refs #7736 by:Carlos Andrés
- feat: refs #6403 add delete by:pablone
- feat: refs #7126 Added manaClaim calc by:guillermo
- feat: refs #7126 Refactor and added columns in bs.waste table & proc by:guillermo
- feat: refs #7197 filter by correcting by:jorgep
- feat: refs #7297 add new columns by:pablone
- feat: refs #7356 new parameters in sql for Weekly tickets front by:Jon
- feat: refs #7401 redirect lilium by:pablone
- feat: refs #7511 Fix tests by:guillermo
- feat: refs #7511 Rename to multiConfig tables by:guillermo
- feat: refs #7589 Added display (item_valuateInventory) by:guillermo
- feat: refs #7589 Added vItemTypeFk & vItemCategoryFk (item_valuateInventory) by:guillermo
- feat: refs #7681 Changes by:guillermo
- feat: refs #7681 Optimization and refactor by:guillermo
- feat: refs #7683 drop temporary table by:robert
- feat: refs #7683 productionControl by:robert
- feat: refs #7728 Added throw due date by:guillermo
- feat: refs #7740 Ticket before update added restriction by:guillermo
- feat(salix): #7648 Add field for endpoint as buyLabel report by:Javier Segarra
- feat(salix): #7648 remove white line by:Javier Segarra
- feat: tabla config dias margen vctos. refs #7728 by:Carlos Andrés
### Changed 📦
- eat: refactor buyUltimate refs #7736 by:Carlos Andrés
- feat: refactor buyUltimate refs #7736 by:Carlos Andrés
- feat: refs #7681 Optimization and refactor by:guillermo
- refactor: refs #7126 Requested changes by:guillermo
- refactor: refs #7511 Minor change by:guillermo
- refactor: refs #7640 Multipleinventory available by:guillermo
- refactor: refs #7681 Changes by:guillermo
- refactor: refs #7681 Requested changes by:guillermo
### Fixed 🛠️
- add prefix (hotFix_liliumRedirection) by:alexm
- fix(client_filter): add recovery by:alexm
- fix: defaulter filter correct sql (6943-fix_defaulter_filter) by:alexm
- fix(deletExpeditions): merge test → dev by:guillermo
- fix: refs #6403 fix mrw cancel shipment return type by:pablone
- fix: refs #7126 Added addressWaste type by:guillermo
- fix: refs #7126 Fix by:guillermo
- fix: refs #7126 Minor change by:guillermo
- fix: refs #7126 Primary key no unique data by:guillermo
- fix: refs #7126 Slow update by:guillermo
- fix: refs #7511 Minor change by:guillermo
- fix: refs #7546 Deleted insert util.binlogQueue by:guillermo
- fix: refs #7811 Variables pm2 by:guillermo
- fix: without path by:alexm
# Version 24.28 - 2024-07-09 # Version 24.28 - 2024-07-09
### Added 🆕 ### Added 🆕

View File

@ -57,8 +57,10 @@ module.exports = Self => {
ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY pickingOrder) currentItemShelving, ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY pickingOrder) currentItemShelving,
COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) totalItemShelving, COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) totalItemShelving,
sh.code, sh.code,
IFNULL(p2.code, p.code) parkingCode, p2.code parkingCode,
IFNULL(p2.pickingOrder, p.pickingOrder) pickingOrder, p2.pickingOrder pickingOrder,
p.code parkingCodePrevia,
p.pickingOrder pickingOrderPrevia,
iss.id itemShelvingSaleFk, iss.id itemShelvingSaleFk,
iss.isPicked iss.isPicked
FROM ticketCollection tc FROM ticketCollection tc
@ -95,8 +97,10 @@ module.exports = Self => {
ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY p.pickingOrder), ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY p.pickingOrder),
COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) , COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) ,
sh.code, sh.code,
IFNULL(p2.code, p.code), p2.code,
IFNULL(p2.pickingOrder, p.pickingOrder), p2.pickingOrder,
p.code,
p.pickingOrder,
iss.id itemShelvingSaleFk, iss.id itemShelvingSaleFk,
iss.isPicked iss.isPicked
FROM sectorCollection sc FROM sectorCollection sc

View File

@ -11,13 +11,6 @@ module.exports = Self => {
arg: 'filter', arg: 'filter',
type: 'object', type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string',
http: {source: 'query'}
},
{
arg: 'search',
type: 'string',
description: 'Value to filter',
http: {source: 'query'}
}, },
], ],
returns: { returns: {
@ -29,13 +22,11 @@ module.exports = Self => {
verb: 'GET', verb: 'GET',
}, },
}); });
Self.filter = async(ctx, filter, options) => { Self.filter = async(filter = {}, options) => {
const myOptions = {}; const myOptions = {};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);
filter = ctx?.filter ?? {};
const conn = Self.dataSource.connector; const conn = Self.dataSource.connector;
const where = buildFilter(filter?.where, (param, value) => { const where = buildFilter(filter?.where, (param, value) => {
switch (param) { switch (param) {
@ -50,7 +41,7 @@ module.exports = Self => {
}; };
} }
}) ?? {}; }) ?? {};
delete ctx.filter.where; delete filter.where;
const stmts = []; const stmts = [];
let stmt; let stmt;
@ -70,11 +61,13 @@ module.exports = Self => {
JOIN country c on c.id = p.countryFk JOIN country c on c.id = p.countryFk
`); `);
stmt.merge(conn.makeSuffix({where, ...ctx})); stmt.merge(conn.makeSuffix({where}));
stmt.merge(conn.makeLimit(filter));
const itemsIndex = stmts.push(stmt) - 1; const itemsIndex = stmts.push(stmt) - 1;
const sql = ParameterizedSQL.join(stmts, ';'); const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql, myOptions); const result = await conn.executeStmt(sql, myOptions);
return itemsIndex === 0 ? result : result[itemsIndex]; return itemsIndex === 0 ? result : result[itemsIndex];
}; };
}; };

View File

@ -6,12 +6,9 @@ describe('Postcode filter()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
try { try {
const ctx = { const results = await models.Postcode.filter({
filter: {
},
limit: 1 limit: 1
}; }, options);
const results = await models.Postcode.filter(ctx, options);
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
await tx.rollback(); await tx.rollback();
@ -26,14 +23,11 @@ describe('Postcode filter()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
try { try {
const ctx = { const results = await models.Postcode.filter({
filter: {
where: { where: {
search: 46, search: 46,
} }
}, }, options);
};
const results = await models.Postcode.filter(ctx, options);
expect(results.length).toEqual(4); expect(results.length).toEqual(4);
await tx.rollback(); await tx.rollback();
@ -48,14 +42,9 @@ describe('Postcode filter()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
try { try {
const ctx = { const results = await models.Postcode.filter({where: {
filter: {
where: {
search: 'Alz', search: 'Alz',
} }}, options);
},
};
const results = await models.Postcode.filter(ctx, options);
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
await tx.rollback(); await tx.rollback();
@ -70,14 +59,9 @@ describe('Postcode filter()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
try { try {
const ctx = { const results = await models.Postcode.filter({where: {
filter: {
where: {
search: 'one', search: 'one',
} }}, options);
},
};
const results = await models.Postcode.filter(ctx, options);
expect(results.length).toEqual(4); expect(results.length).toEqual(4);
await tx.rollback(); await tx.rollback();
@ -92,14 +76,11 @@ describe('Postcode filter()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
try { try {
const ctx = { const results = await models.Postcode.filter({
filter: {
where: { where: {
search: 'Ec', search: 'Ec',
} }
}, }, options);
};
const results = await models.Postcode.filter(ctx, options);
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
await tx.rollback(); await tx.rollback();

View File

@ -30,16 +30,10 @@ module.exports = Self => {
// Schedule to remove current token // Schedule to remove current token
setTimeout(async() => { setTimeout(async() => {
let exists;
try { try {
exists = await models.AccessToken.findById(token.id); await Self.logout(token.id);
exists && await Self.logout(token.id);
} catch (error) { } catch (error) {
// eslint-disable-next-line no-console // FIXME: Crash if do throw new Error(error)
console.error(error);
const body = {error: error.message, now: Date.now(), userId: token?.userId ?? null, exists};
await handleError(body);
throw new Error(error);
} }
}, courtesyTime * 1000); }, courtesyTime * 1000);
@ -53,14 +47,20 @@ module.exports = Self => {
return {id: accessToken.id, ttl: accessToken.ttl}; return {id: accessToken.id, ttl: accessToken.ttl};
} catch (error) { } catch (error) {
const body = {error: error.message, now: Date.now(), userId: token?.userId ?? null, createTokenOptions, isNotExceeded}; const body = {
await handleError(body); error: error.message,
userId: token?.userId ?? null,
token: token?.id,
scopes: token?.scopes,
createTokenOptions,
isNotExceeded
};
await handleError(JSON.stringify(body));
throw new Error(error); throw new Error(error);
} }
}; };
}; };
async function handleError(body, tag = 'renewToken') { async function handleError(body) {
body = JSON.stringify(body); await models.Application.rawSql('CALL util.debugAdd(?,?);', ['renewToken', body]);
await models.Application.rawSql('CALL util.debugAdd(?,?);', [tag, body]);
} }

View File

@ -67,7 +67,9 @@ module.exports = Self => {
if (vnUser.twoFactor === 'email') { if (vnUser.twoFactor === 'email') {
const $ = Self.app.models; const $ = Self.app.models;
const code = String(Math.floor(Math.random() * 999999)); const min = 100000;
const max = 999999;
const code = String(Math.floor(Math.random() * (max - min + 1)) + min);
const maxTTL = ((60 * 1000) * 5); // 5 min const maxTTL = ((60 * 1000) * 5); // 5 min
await $.AuthCode.upsertWithWhere({userFk: vnUser.id}, { await $.AuthCode.upsertWithWhere({userFk: vnUser.id}, {
userFk: vnUser.id, userFk: vnUser.id,

View File

@ -24,6 +24,10 @@ module.exports = Self => {
arg: 'lang', arg: 'lang',
type: 'string', type: 'string',
description: 'The user lang' description: 'The user lang'
}, {
arg: 'twoFactor',
type: 'string',
description: 'The user twoFactor'
} }
], ],
http: { http: {
@ -32,8 +36,8 @@ module.exports = Self => {
} }
}); });
Self.updateUser = async(ctx, id, name, nickname, email, lang) => { Self.updateUser = async(ctx, id, name, nickname, email, lang, twoFactor) => {
await Self.userSecurity(ctx, id); await Self.userSecurity(ctx, id);
await Self.upsertWithWhere({id}, {name, nickname, email, lang}); await Self.upsertWithWhere({id}, {name, nickname, email, lang, twoFactor});
}; };
}; };

View File

@ -58,7 +58,7 @@ module.exports = Self => {
fields: ['name', 'twoFactor'] fields: ['name', 'twoFactor']
}, myOptions); }, myOptions);
if (user.name !== username) if (user.name.toLowerCase() !== username.toLowerCase())
throw new UserError('Authentication failed'); throw new UserError('Authentication failed');
await authCode.destroy(myOptions); await authCode.destroy(myOptions);

View File

@ -0,0 +1,50 @@
module.exports = Self => {
Self.remoteMethodCtx('add', {
description: 'Add activity if the activity is different or is the same but have exceed time for break',
accessType: 'WRITE',
accepts: [
{
arg: 'code',
type: 'string',
description: 'Code for activity'
},
{
arg: 'model',
type: 'string',
description: 'Origin model from insert'
},
],
http: {
path: `/add`,
verb: 'POST'
}
});
Self.add = async(ctx, code, model, options) => {
const userId = ctx.req.accessToken.userId;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
return await Self.rawSql(`
INSERT INTO workerActivity (workerFk, workerActivityTypeFk, model)
SELECT ?, ?, ?
FROM workerTimeControlParams wtcp
LEFT JOIN (
SELECT wa.workerFk,
wa.created,
wat.code
FROM workerActivity wa
LEFT JOIN workerActivityType wat ON wat.code = wa.workerActivityTypeFk
WHERE wa.workerFk = ?
ORDER BY wa.created DESC
LIMIT 1
) sub ON TRUE
WHERE sub.workerFk IS NULL
OR sub.code <> ?
OR TIMESTAMPDIFF(SECOND, sub.created, util.VN_NOW()) > wtcp.dayBreak;`
, [userId, code, model, userId, code], myOptions);
};
};

View File

@ -0,0 +1,30 @@
const {models} = require('vn-loopback');
describe('workerActivity insert()', () => {
const ctx = beforeAll.getCtx(1106);
it('should insert in workerActivity', async() => {
const tx = await models.WorkerActivity.beginTransaction({});
let count = 0;
const options = {transaction: tx};
try {
await models.WorkerActivityType.create(
{'code': 'STOP', 'description': 'STOP'}, options
);
await models.WorkerActivity.add(ctx, 'STOP', 'APP', options);
count = await models.WorkerActivity.count(
{'workerFK': 1106}, options
);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
expect(count).toEqual(1);
});
});

View File

@ -28,6 +28,9 @@
"Company": { "Company": {
"dataSource": "vn" "dataSource": "vn"
}, },
"Config": {
"dataSource": "vn"
},
"Continent": { "Continent": {
"dataSource": "vn" "dataSource": "vn"
}, },
@ -115,6 +118,9 @@
"NotificationSubscription": { "NotificationSubscription": {
"dataSource": "vn" "dataSource": "vn"
}, },
"OrmConfig": {
"dataSource": "vn"
},
"Province": { "Province": {
"dataSource": "vn" "dataSource": "vn"
}, },

22
back/models/config.json Normal file
View File

@ -0,0 +1,22 @@
{
"name": "Config",
"base": "VnModel",
"options": {
"mysql": {
"table": "config"
}
},
"properties": {
"inventoried": {
"type": "date"
}
},
"acls": [
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
}
]
}

View File

@ -0,0 +1,26 @@
{
"name": "OrmConfig",
"base": "VnModel",
"options": {
"mysql": {
"table": "ormConfig"
}
},
"properties": {
"id": {
"type": "number",
"id": true
},
"selectLimit": {
"type": "number"
}
},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
}
]
}

View File

@ -9,7 +9,8 @@
"properties": { "properties": {
"code": { "code": {
"id": true, "id": true,
"type": "string" "type": "string",
"required": true
} }
}, },
"relations": { "relations": {

View File

@ -12,7 +12,8 @@
"type": "number" "type": "number"
}, },
"name": { "name": {
"type": "string" "type": "string",
"required": true
} }
}, },
"relations": { "relations": {

View File

@ -101,9 +101,10 @@ module.exports = function(Self) {
const headers = httpRequest.headers; const headers = httpRequest.headers;
const origin = headers.origin; const origin = headers.origin;
const defaultHash = '/reset-password?access_token=$token$'; const defaultHash = '!/reset-password?access_token=$token$';
const recoverHashes = { const recoverHashes = {
hedera: 'verificationToken=$token$' hedera: '!verificationToken=$token$',
lilium: '/resetPassword?access_token=$token$'
}; };
const app = info.options?.app; const app = info.options?.app;
@ -115,7 +116,7 @@ module.exports = function(Self) {
const params = { const params = {
recipient: info.email, recipient: info.email,
lang: user.lang, lang: user.lang,
url: origin + '/#!' + recoverHash url: origin + '/#' + recoverHash
}; };
const options = Object.assign({}, info.options); const options = Object.assign({}, info.options);

View File

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

View File

@ -22,6 +22,7 @@
}, },
"description": { "description": {
"type": "string" "type": "string"
}
}, },
"relations": { "relations": {
"workerFk": { "workerFk": {
@ -35,5 +36,4 @@
"foreignKey": "workerActivityTypeFk" "foreignKey": "workerActivityTypeFk"
} }
} }
}
} }

View File

@ -2,6 +2,6 @@ apps:
- script: ./loopback/server/server.js - script: ./loopback/server/server.js
name: salix-back name: salix-back
instances: 1 instances: 1
max_restarts: 3 max_restarts: 0
restart_delay: 15000 autorestart: false
node_args: --tls-min-v1.0 --openssl-legacy-provider node_args: --tls-min-v1.0 --openssl-legacy-provider

File diff suppressed because it is too large Load Diff

View File

@ -1292,6 +1292,8 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','buffer','juan@db-p
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','greuge','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','greuge','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','item','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select,Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','item','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select,Update');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','itemShelving','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','itemShelving','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','agencyIncoming','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','addressObservation','carlosap@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','negativeOrigin','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','negativeOrigin','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','Vehiculos_consumo','carlosap@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','Vehiculos_consumo','carlosap@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','entryOrder','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','entryOrder','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
@ -1357,6 +1359,8 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','accounting',
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','accounting','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','accounting','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerActivity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerActivity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketRequest','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketRequest','guillermo@10.5.1.3','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','Vehiculos_consumo','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budgetState','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','vehicleState','jgallego@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','vehicleState','jgallego@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','expeditionState','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','expeditionState','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','specialPrice','jgallego@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','specialPrice','jgallego@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
@ -1379,6 +1383,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','professionalCategor
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','ticketObservation','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','ticketObservation','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryNoteState','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryNoteState','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryNote','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryNote','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','inventoryConfig','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','comparative','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','comparative','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','invoiceOutExpense','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','invoiceOutExpense','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','delivery','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','delivery','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
@ -1404,6 +1409,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','teamBoss','business','guiller
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketServiceType','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketServiceType','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','business','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','business','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierAgencyTerm','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierAgencyTerm','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemMinimumQuantity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientRate','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientRate','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','entryEditor','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','entryEditor','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert','Update');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientInforma','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientInforma','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
@ -1428,6 +1434,8 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','businessReasonEnd','guil
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buySource','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buySource','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','bi','salesPerson','claims_ratio','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','bi','salesPerson','claims_ratio','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','shelfMultiConfig','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientConfig','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_gestdoc','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_gestdoc','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_state','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_state','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
@ -1447,6 +1455,11 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','accountingType','gu
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','bankPolicyDetail','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','bankPolicyDetail','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','bankPolicyReview','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','bankPolicyReview','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','bankPolicy','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','bankPolicy','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','edi','hedera-web','imapMultiConfig','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','salesAssistant','orderConfig','root@localhost','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemEntryOut','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemEntryIn','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemShelvingSale','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
/*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */;
/*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */; /*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */;
@ -2152,9 +2165,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_recalcPricesByAwb'
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_recalcPricesByEntry','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_recalcPricesByEntry','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','util','hr','accountNumberToIban','FUNCTION','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','hr','accountNumberToIban','FUNCTION','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','util','financial','accountNumberToIban','FUNCTION','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','financial','accountNumberToIban','FUNCTION','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','supplier_statement','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','supplier_statementWithEntries','PROCEDURE','guillermo@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','supplier_statement','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hrBoss','supplier_statement','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','XDiario_check','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','XDiario_check','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','travel_getDetailFromContinent','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','travel_getDetailFromContinent','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','entry_getTransfer','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','entry_getTransfer','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
@ -2185,6 +2196,8 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemShelvingSale_
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','sectorCollection_getMyPartial','PROCEDURE','carlosap@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','sectorCollection_getMyPartial','PROCEDURE','carlosap@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana-write','item_ValuateInventory','PROCEDURE','guillermo@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana-write','item_ValuateInventory','PROCEDURE','guillermo@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','guest','ticketCalculatePurge','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','guest','ticketCalculatePurge','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','cooler','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
/*!40000 ALTER TABLE `procs_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `procs_priv` ENABLE KEYS */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
@ -2229,7 +2242,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','grafana-write','{\"access\":0,\"ve
INSERT IGNORE INTO `global_priv` VALUES ('','greenhouseBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','greenhouseBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
INSERT IGNORE INTO `global_priv` VALUES ('','guest','{\"access\": 0, \"max_questions\": 40000, \"max_updates\": 1000, \"max_connections\": 150000, \"max_user_connections\": 200, \"max_statement_time\": 0.000000, \"is_role\": true, \"version_id\": 101106}'); INSERT IGNORE INTO `global_priv` VALUES ('','guest','{\"access\": 0, \"max_questions\": 40000, \"max_updates\": 1000, \"max_connections\": 150000, \"max_user_connections\": 200, \"max_statement_time\": 0.000000, \"is_role\": true, \"version_id\": 101106}');
INSERT IGNORE INTO `global_priv` VALUES ('','handmadeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','handmadeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
INSERT IGNORE INTO `global_priv` VALUES ('','hedera-web','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','hedera-web','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
INSERT IGNORE INTO `global_priv` VALUES ('','hr','{\"access\": 0, \"is_role\": true, \"version_id\": 101106}'); INSERT IGNORE INTO `global_priv` VALUES ('','hr','{\"access\": 0, \"is_role\": true, \"version_id\": 101106}');
INSERT IGNORE INTO `global_priv` VALUES ('','hrBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','hrBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
INSERT IGNORE INTO `global_priv` VALUES ('','invoicing','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','invoicing','{\"access\":0,\"version_id\":100707,\"is_role\":true}');

File diff suppressed because it is too large Load Diff

View File

@ -1423,6 +1423,70 @@ DELIMITER ;
-- --
USE `salix`; USE `salix`;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `salix`.`ACL_beforeInsert`
BEFORE INSERT ON `ACL`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `salix`.`ACL_beforeUpdate`
BEFORE UPDATE ON `ACL`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `salix`.`ACL_afterDelete`
AFTER DELETE ON `ACL`
FOR EACH ROW
BEGIN
INSERT INTO ACLLog
SET `action` = 'delete',
`changedModel` = 'Acl',
`changedModelId` = OLD.id,
`userFk` = account.myUser_getId();
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
-- --
-- Current Database: `srt` -- Current Database: `srt`
@ -6325,10 +6389,6 @@ BEGIN
SET NEW.userFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId();
END IF; END IF;
IF (NEW.visible <> OLD.visible) THEN
SET NEW.available = GREATEST(NEW.available + NEW.visible - OLD.visible, 0);
END IF;
END */;; END */;;
DELIMITER ; DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET sql_mode = @saved_sql_mode */ ;
@ -9224,13 +9284,22 @@ BEGIN
SET NEW.editorFk = account.myUser_getId(); SET NEW.editorFk = account.myUser_getId();
IF NOT (NEW.routeFk <=> OLD.routeFk) THEN IF NOT (NEW.routeFk <=> OLD.routeFk) THEN
INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) IF NEW.isSigned AND NOT (
SELECT r.id SELECT (COUNT(s.id) = COUNT(cb.saleFk)
FROM vn.route r AND SUM(s.quantity) = SUM(cb.quantity))
WHERE r.isOk = FALSE FROM sale s
AND r.id IN (OLD.routeFk,NEW.routeFk) LEFT JOIN claimBeginning cb ON cb.saleFk = s.id
AND r.created >= util.VN_CURDATE() WHERE s.ticketFk = NEW.id
GROUP BY r.id; ) THEN
CALL util.throw('A signed ticket cannot be rerouted');
END IF;
INSERT IGNORE INTO routeRecalc(routeFk)
SELECT id
FROM `route`
WHERE NOT isOk
AND id IN (OLD.routeFk, NEW.routeFk)
AND created >= util.VN_CURDATE()
GROUP BY id;
END IF; END IF;
IF NOT (DATE(NEW.shipped) <=> DATE(OLD.shipped)) THEN IF NOT (DATE(NEW.shipped) <=> DATE(OLD.shipped)) THEN
@ -11143,4 +11212,4 @@ USE `vn2008`;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2024-07-23 8:19:41 -- Dump completed on 2024-08-20 7:45:23

View File

@ -412,7 +412,7 @@ INSERT INTO `vn`.`clientManaCache`(`clientFk`, `mana`, `dated`)
(1103, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (1103, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)),
(1104, -30, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)); (1104, -30, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH));
INSERT INTO `vn`.`mandateType`(`id`, `name`) INSERT INTO `vn`.`mandateType`(`id`, `code`)
VALUES VALUES
(1, 'B2B'), (1, 'B2B'),
(2, 'CORE'), (2, 'CORE'),
@ -633,7 +633,7 @@ INSERT INTO `vn`.`invoiceOutSerial` (`code`, `description`, `isTaxed`, `taxAreaF
('A', 'Global nacional', 1, 'NATIONAL', 0, 'global'), ('A', 'Global nacional', 1, 'NATIONAL', 0, 'global'),
('T', 'Española rapida', 1, 'NATIONAL', 0, 'quick'), ('T', 'Española rapida', 1, 'NATIONAL', 0, 'quick'),
('V', 'Intracomunitaria global', 0, 'CEE', 1, 'global'), ('V', 'Intracomunitaria global', 0, 'CEE', 1, 'global'),
('M', 'Múltiple nacional', 1, 'NATIONAL', 0, 'quick'), ('M', 'Múltiple nacional', 1, 'NATIONAL', 0, 'multiple'),
('R', 'Rectificativa', 1, 'NATIONAL', 0, NULL), ('R', 'Rectificativa', 1, 'NATIONAL', 0, NULL),
('E', 'Exportación rápida', 0, 'WORLD', 0, 'quick'); ('E', 'Exportación rápida', 0, 'WORLD', 0, 'quick');
@ -744,45 +744,45 @@ INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agen
(6, NULL, 57, util.VN_CURDATE(), 5, 7, 'sixth route', 1.7, 60, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 3), (6, NULL, 57, util.VN_CURDATE(), 5, 7, 'sixth route', 1.7, 60, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 3),
(7, NULL, 57, util.VN_CURDATE(), 6, 8, 'seventh route', 0, 70, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 5); (7, NULL, 57, util.VN_CURDATE(), 6, 8, 'seventh route', 0, 70, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 5);
INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`, `weight`, `cmrFk`) INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`, `weight`, `cmrFk`, `problem`, `risk`)
VALUES VALUES
(1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1), (1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1, 'hasHighRisk', 901.4),
(2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 1, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 2), (2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 1, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 2, 'hasHighRisk', 901.4),
(3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), NULL, 3), (3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), NULL, 3, NULL, NULL),
(4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), NULL, NULL), (4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), NULL, NULL, NULL, NULL),
(5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), NULL, NULL), (5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), NULL, NULL, NULL, NULL),
(6 , 1, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), NULL, NULL), (6 , 1, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), NULL, NULL, 'hasHighRisk', 901.4),
(7 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), (7 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL, 'hasHighRisk', 901.4),
(8 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Bat cave', 121, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), (8 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Bat cave', 121, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL, 'hasHighRisk', 901.4),
(9 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), (9 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(10, 1, 1, 5, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'Ingram Street', 2, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (10, 1, 1, 5, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'Ingram Street', 2, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL, 'isTooLittle', NULL),
(11, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), (11, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL, 'hasTicketRequest', NULL),
(12, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (12, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(13, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), (13, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(14, 1, 2, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1104, 'Malibu Point', 4, NULL, 0, 9, 5, 1, util.VN_CURDATE(), NULL, NULL), (14, 1, 2, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1104, 'Malibu Point', 4, NULL, 0, 9, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(15, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1105, 'An incredibly long alias for testing purposes', 125, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), (15, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1105, 'An incredibly long alias for testing purposes', 125, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL, 'isFreezed', NULL),
(16, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), (16, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, 388.7),
(17, 1, 7, 2, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), (17, 1, 7, 2, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, 388.7),
(18, 1, 4, 4, 4, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1108, 'Cerebro', 128, NULL, 0, 12, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +12 HOUR), NULL, NULL), (18, 1, 4, 4, 4, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1108, 'Cerebro', 128, NULL, 0, 12, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +12 HOUR), NULL, NULL, 'isFreezed', NULL),
(19, 1, 5, 5, NULL, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 1, NULL, 5, 1, util.VN_CURDATE(), NULL, NULL), (19, 1, 5, 5, NULL, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 1, NULL, 5, 1, util.VN_CURDATE(), NULL, NULL, 'isTaxDataChecked', NULL),
(20, 1, 5, 5, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL), (20, 1, 5, 5, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL, 'isTaxDataChecked', NULL),
(21, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Holland', 102, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL), (21, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Holland', 102, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL, 'isTaxDataChecked', NULL),
(22, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Japan', 103, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL), (22, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Japan', 103, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL, 'isTaxDataChecked', NULL),
(23, NULL, 8, 1, 7, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'address 21', 121, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL, NULL), (23, NULL, 8, 1, 7, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'address 21', 121, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL, NULL, 'hasTicketRequest, hasHighRisk', 901.4),
(24 ,NULL, 8, 1, 7, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL, NULL), (24 ,NULL, 8, 1, 7, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL, NULL, 'hasHighRisk', 901.4),
(25 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (25 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL, 'hasHighRisk', 901.4),
(26 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'An incredibly long alias for testing purposes', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (26 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'An incredibly long alias for testing purposes', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL, 'hasHighRisk', 901.4),
(27 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Wolverine', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (27 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Wolverine', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, 901.4),
(28, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (28, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(29, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (29, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(30, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (30, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(33, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), (33, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(34, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1103, 'BEJAR', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), (34, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1103, 'BEJAR', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(35, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Somewhere in Philippines', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), (35, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Somewhere in Philippines', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(36, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Ant-Man Adventure', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), (36, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Ant-Man Adventure', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL, NULL, NULL),
(37, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1110, 'Deadpool swords', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL); (37, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1110, 'Deadpool swords', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL, NULL, NULL);
INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`)
VALUES VALUES
@ -1060,50 +1060,50 @@ INSERT INTO `vn`.`ticketPackaging`(`id`, `ticketFk`, `packagingFk`, `quantity`,
(2, 2, 2, 1, util.VN_CURDATE(), NULL), (2, 2, 2, 1, util.VN_CURDATE(), NULL),
(3, 3, 2, 4, util.VN_CURDATE(), NULL); (3, 3, 2, 4, util.VN_CURDATE(), NULL);
INSERT INTO `vn`.`sale`(`id`, `itemFk`, `ticketFk`, `concept`, `quantity`, `price`, `discount`, `reserved`, `isPicked`, `created`) INSERT INTO `vn`.`sale`(`id`, `itemFk`, `ticketFk`, `concept`, `quantity`, `price`, `discount`, `reserved`, `isPicked`, `created`, `problem`)
VALUES VALUES
(1, 1, 1, 'Ranged weapon longbow 200cm', 5, 100.39, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (1, 1, 1, 'Ranged weapon longbow 200cm', 5, 100.39, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 'hasComponentLack'),
(2, 2, 1, 'Melee weapon combat fist 15cm', 10, 7.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (2, 2, 1, 'Melee weapon combat fist 15cm', 10, 7.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 'hasComponentLack'),
(3, 1, 1, 'Ranged weapon longbow 200cm', 2, 100.39, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (3, 1, 1, 'Ranged weapon longbow 200cm', 2, 100.39, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 'hasComponentLack'),
(4, 4, 1, 'Melee weapon heavy shield 100cm', 20, 1.69, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (4, 4, 1, 'Melee weapon heavy shield 100cm', 20, 1.69, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 'hasComponentLack'),
(5, 1, 2, 'Ranged weapon longbow 200cm', 1, 110.33, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (5, 1, 2, 'Ranged weapon longbow 200cm', 1, 110.33, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 'hasComponentLack'),
(6, 1, 3, 'Ranged weapon longbow 200cm', 1, 110.33, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), (6, 1, 3, 'Ranged weapon longbow 200cm', 1, 110.33, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 'hasComponentLack'),
(7, 2, 11, 'Melee weapon combat fist 15cm', 15, 7.74, 0, 0, 0, util.VN_CURDATE()), (7, 2, 11, 'Melee weapon combat fist 15cm', 15, 7.74, 0, 0, 0, util.VN_CURDATE(), NULL),
(8, 4, 11, 'Melee weapon heavy shield 100cm', 10, 1.79, 0, 0, 0, util.VN_CURDATE()), (8, 4, 11, 'Melee weapon heavy shield 100cm', 10, 1.79, 0, 0, 0, util.VN_CURDATE(), NULL),
(9, 1, 16, 'Ranged weapon longbow 200cm', 1, 103.49, 0, 0, 0, util.VN_CURDATE()), (9, 1, 16, 'Ranged weapon longbow 200cm', 1, 103.49, 0, 0, 0, util.VN_CURDATE(), NULL),
(10, 2, 16, 'Melee weapon combat fist 15cm', 10, 7.09, 0, 0, 0, util.VN_CURDATE()), (10, 2, 16, 'Melee weapon combat fist 15cm', 10, 7.09, 0, 0, 0, util.VN_CURDATE(), NULL),
(11, 1, 16, 'Ranged weapon longbow 200cm', 1, 103.49, 0, 0, 0, util.VN_CURDATE()), (11, 1, 16, 'Ranged weapon longbow 200cm', 1, 103.49, 0, 0, 0, util.VN_CURDATE(), NULL),
(12, 4, 16, 'Melee weapon heavy shield 100cm', 20, 1.71, 0, 0, 0, util.VN_CURDATE()), (12, 4, 16, 'Melee weapon heavy shield 100cm', 20, 1.71, 0, 0, 0, util.VN_CURDATE(), NULL),
(13, 2, 8, 'Melee weapon combat fist 15cm', 10, 7.08, 0, 0, 0, util.VN_CURDATE()), (13, 2, 8, 'Melee weapon combat fist 15cm', 10, 7.08, 0, 0, 0, util.VN_CURDATE(), NULL),
(14, 1, 8, 'Ranged weapon longbow 200cm', 2, 103.49, 0, 0, 0, util.VN_CURDATE()), (14, 1, 8, 'Ranged weapon longbow 200cm', 2, 103.49, 0, 0, 0, util.VN_CURDATE(), NULL),
(15, 1, 19, 'Ranged weapon longbow 200cm', 1, 103.49, 0, 0, 0, util.VN_CURDATE()), (15, 1, 19, 'Ranged weapon longbow 200cm', 1, 103.49, 0, 0, 0, util.VN_CURDATE(), NULL),
(16, 2, 20, 'Melee weapon combat fist 15cm', 20, 7.07, 0, 0, 0, util.VN_CURDATE()), (16, 2, 20, 'Melee weapon combat fist 15cm', 20, 7.07, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(17, 2, 22, 'Melee weapon combat fist 15cm', 30, 7.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH)), (17, 2, 22, 'Melee weapon combat fist 15cm', 30, 7.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), 'hasComponentLack'),
(18, 4, 22, 'Melee weapon heavy shield 100cm', 20, 1.69, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH)), (18, 4, 22, 'Melee weapon heavy shield 100cm', 20, 1.69, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), 'hasComponentLack'),
(19, 1, 4, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH)), (19, 1, 4, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), 'hasComponentLack'),
(20, 1, 5, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH)), (20, 1, 5, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), 'hasComponentLack'),
(21, 1, 6, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (21, 1, 6, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 'hasComponentLack'),
(22, 1, 7, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, util.VN_CURDATE()), (22, 1, 7, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(23, 1, 9, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, util.VN_CURDATE()), (23, 1, 9, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(24, 1, 10, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, util.VN_CURDATE()), (24, 1, 10, 'Ranged weapon longbow 200cm', 1, 8.07, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(25, 4, 12, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (25, 4, 12, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(26, 4, 13, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (26, 4, 13, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(27, 4, 14, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (27, 4, 14, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(28, 4, 15, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (28, 4, 15, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(29, 4, 17, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (29, 4, 17, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(30, 4, 18, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (30, 4, 18, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(31, 2, 23, 'Melee weapon combat fist 15cm', -5, 7.08, 0, 0, 0, util.VN_CURDATE()), (31, 2, 23, 'Melee weapon combat fist 15cm', -5, 7.08, 0, 0, 0, util.VN_CURDATE(), NULL),
(32, 1, 24, 'Ranged weapon longbow 200cm', -1, 8.07, 0, 0, 0, util.VN_CURDATE()), (32, 1, 24, 'Ranged weapon longbow 200cm', -1, 8.07, 0, 0, 0, util.VN_CURDATE(), NULL),
(33, 5, 14, 'Ranged weapon pistol 9mm', 50, 1.79, 0, 0, 0, util.VN_CURDATE()), (33, 5, 14, 'Ranged weapon pistol 9mm', 50, 1.79, 0, 0, 0, util.VN_CURDATE(), NULL),
(34, 4, 28, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (34, 4, 28, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(35, 4, 29, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (35, 4, 29, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(37, 4, 31, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (37, 4, 31, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE(), NULL),
(36, 4, 30, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (36, 4, 30, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(38, 2, 32, 'Melee weapon combat fist 15cm', 30, 7.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH)), (38, 2, 32, 'Melee weapon combat fist 15cm', 30, 7.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), 'hasComponentLack'),
(39, 1, 32, 'Ranged weapon longbow 200cm', 2, 103.49, 0, 0, 0, util.VN_CURDATE()), (39, 1, 32, 'Ranged weapon longbow 200cm', 2, 103.49, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(40, 2, 34, 'Melee weapon combat fist 15cm', 10.00, 3.91, 0, 0, 0, util.VN_CURDATE()), (40, 2, 34, 'Melee weapon combat fist 15cm', 10.00, 3.91, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(41, 2, 35, 'Melee weapon combat fist 15cm', 8.00, 3.01, 0, 0, 0, util.VN_CURDATE()), (41, 2, 35, 'Melee weapon combat fist 15cm', 8.00, 3.01, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack'),
(42, 2, 36, 'Melee weapon combat fist 15cm', 6.00, 2.50, 0, 0, 0, util.VN_CURDATE()); (42, 2, 36, 'Melee weapon combat fist 15cm', 6.00, 2.50, 0, 0, 0, util.VN_CURDATE(), 'hasComponentLack');
INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`) INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`)
VALUES VALUES
@ -1520,7 +1520,7 @@ INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed
INSERT INTO `vn`.`entryConfig` (`defaultEntry`, `inventorySupplierFk`, `defaultSupplierFk`) INSERT INTO `vn`.`entryConfig` (`defaultEntry`, `inventorySupplierFk`, `defaultSupplierFk`)
VALUES (2, 4, 1); VALUES (2, 4, 1);
INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleQuantity`, `saleInternalWaste`, `saleExternalWaste`) INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleWasteQuantity`, `saleInternalWaste`, `saleExternalWaste`)
VALUES VALUES
('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 1, 1, '1062', '51', '56.20', '56.20'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 1, 1, '1062', '51', '56.20', '56.20'),
('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 2, 1, '35074', '687', '53.12', '89.69'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 2, 1, '35074', '687', '53.12', '89.69'),
@ -3949,11 +3949,11 @@ VALUES
(35, 'ES12346B12345679', 3, 241); (35, 'ES12346B12345679', 3, 241);
INSERT INTO vn.accountDetailType INSERT INTO vn.accountDetailType
(id, description) (id, description, code)
VALUES VALUES
(1, 'IBAN'), (1, 'IBAN', 'iban'),
(2, 'SWIFT'), (2, 'SWIFT', 'swift'),
(3, 'Referencia Remesas'), (3, 'Referencia Remesas', 'remRef'),
(4, 'Referencia Transferencias'), (4, 'Referencia Transferencias', 'trnRef'),
(5, 'Referencia Nominas'), (5, 'Referencia Nominas', 'payRef'),
(6, 'ABA'); (6, 'ABA', 'aba');

View File

@ -1,7 +1,7 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`() CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`()
BEGIN BEGIN
DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY; DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(util.VN_CURDATE()) DAY;
DECLARE vDateTo DATE DEFAULT vDateFrom + INTERVAL 6 DAY; DECLARE vDateTo DATE DEFAULT vDateFrom + INTERVAL 6 DAY;
CALL cache.last_buy_refresh(FALSE); CALL cache.last_buy_refresh(FALSE);
@ -12,25 +12,22 @@ BEGIN
it.workerFk, it.workerFk,
it.id, it.id,
s.itemFk, s.itemFk,
SUM(s.quantity), SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity),
SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity) `value`, SUM(IF(aw.`type`, s.quantity, 0)),
SUM ( SUM(
IF( IF(
aw.`type` = 'internal', aw.`type` = 'internal',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
0 0
) )
) internalWaste, ),
SUM ( SUM(
IF( IF(
aw.`type` = 'external', aw.`type` = 'external',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
IF(c.code = 'manaClaim',
sc.value * s.quantity,
0 0
) )
) )
) externalWaste
FROM vn.sale s FROM vn.sale s
JOIN vn.item i ON i.id = s.itemFk JOIN vn.item i ON i.id = s.itemFk
JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.itemType it ON it.id = i.typeFk
@ -41,10 +38,8 @@ BEGIN
JOIN cache.last_buy lb ON lb.item_id = i.id JOIN cache.last_buy lb ON lb.item_id = i.id
AND lb.warehouse_id = w.id AND lb.warehouse_id = w.id
JOIN vn.buy b ON b.id = lb.buy_id JOIN vn.buy b ON b.id = lb.buy_id
LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id
LEFT JOIN vn.component c ON c.id = sc.componentFk
WHERE t.shipped BETWEEN vDateFrom AND vDateTo WHERE t.shipped BETWEEN vDateFrom AND vDateTo
AND w.isManaged AND w.isManaged
GROUP BY it.id, i.id; GROUP BY i.id;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -30,7 +30,7 @@ proc: BEGIN
SELECT inventoried INTO started FROM vn.config LIMIT 1; SELECT inventoried INTO started FROM vn.config LIMIT 1;
SET ended = util.VN_CURDATE(); -- TIMESTAMPADD(DAY, -1, util.VN_CURDATE()); SET ended = util.VN_CURDATE(); -- TIMESTAMPADD(DAY, -1, util.VN_CURDATE());
CALL vn.buyUltimateFromInterval(NULL, started, ended); CALL vn.buy_getUltimateFromInterval(NULL, NULL, started, ended);
DELETE FROM last_buy; DELETE FROM last_buy;

View File

@ -1,59 +1,62 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_confirmWithUser`(vSelf INT, vUserId INT) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_confirmWithUser`(
vSelf INT,
vUserFk INT
)
BEGIN BEGIN
/** /**
* Confirms an order, creating each of its tickets on the corresponding * Confirms an order, creating each of its tickets
* date, store and user. * on the corresponding date, store and user.
* *
* @param vSelf The order identifier * @param vSelf The order identifier
* @param vUser The user identifier * @param vUser The user identifier
*/ */
DECLARE vOk BOOL; DECLARE vHasRows BOOL;
DECLARE vDone BOOL DEFAULT FALSE; DECLARE vDone BOOL;
DECLARE vWarehouse INT; DECLARE vWarehouseFk INT;
DECLARE vShipment DATE; DECLARE vShipment DATE;
DECLARE vTicket INT; DECLARE vShipmentDayEnd DATETIME;
DECLARE vTicketFk INT;
DECLARE vNotes VARCHAR(255); DECLARE vNotes VARCHAR(255);
DECLARE vItem INT; DECLARE vItemFk INT;
DECLARE vConcept VARCHAR(30); DECLARE vConcept VARCHAR(30);
DECLARE vAmount INT; DECLARE vAmount INT;
DECLARE vAvailable INT;
DECLARE vPrice DECIMAL(10,2); DECLARE vPrice DECIMAL(10,2);
DECLARE vSale INT; DECLARE vSaleFk INT;
DECLARE vRate INT; DECLARE vRowFk INT;
DECLARE vRowId INT;
DECLARE vPriceFixed DECIMAL(10,2); DECLARE vPriceFixed DECIMAL(10,2);
DECLARE vDelivery DATE; DECLARE vLanded DATE;
DECLARE vAddress INT; DECLARE vAddressFk INT;
DECLARE vIsConfirmed BOOL; DECLARE vClientFk INT;
DECLARE vClientId INT; DECLARE vCompanyFk INT;
DECLARE vCompanyId INT; DECLARE vAgencyModeFk INT;
DECLARE vAgencyModeId INT; DECLARE vCalcFk INT;
DECLARE TICKET_FREE INT DEFAULT 2;
DECLARE vCalc INT;
DECLARE vIsLogifloraItem BOOL;
DECLARE vOldQuantity INT;
DECLARE vNewQuantity INT;
DECLARE vIsTaxDataChecked BOOL; DECLARE vIsTaxDataChecked BOOL;
DECLARE cDates CURSOR FOR DECLARE vDates CURSOR FOR
SELECT zgs.shipped, r.warehouse_id SELECT zgs.shipped, r.warehouseFk
FROM `order` o FROM `order` o
JOIN order_row r ON r.order_id = o.id JOIN orderRow r ON r.orderFk = o.id
LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouseFk
WHERE o.id = vSelf AND r.amount != 0 WHERE o.id = vSelf
GROUP BY r.warehouse_id; AND r.amount
GROUP BY r.warehouseFk;
DECLARE cRows CURSOR FOR DECLARE vRows CURSOR FOR
SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate, i.isFloramondo SELECT r.id,
FROM order_row r r.itemFk,
JOIN vn.item i ON i.id = r.item_id i.name,
WHERE r.amount != 0 r.amount,
AND r.warehouse_id = vWarehouse r.price
AND r.order_id = vSelf FROM orderRow r
JOIN vn.item i ON i.id = r.itemFk
WHERE r.amount
AND r.warehouseFk = vWarehouseFk
AND r.orderFk = vSelf
ORDER BY r.rate DESC; ORDER BY r.rate DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN BEGIN
@ -62,26 +65,36 @@ BEGIN
END; END;
-- Carga los datos del pedido -- Carga los datos del pedido
SELECT o.date_send, o.address_id, o.note, a.clientFk, SELECT o.date_send,
o.company_id, o.agency_id, c.isTaxDataChecked o.address_id,
INTO vDelivery, vAddress, vNotes, vClientId, o.note,
vCompanyId, vAgencyModeId, vIsTaxDataChecked a.clientFk,
FROM hedera.`order` o o.company_id,
o.agency_id,
c.isTaxDataChecked
INTO vLanded,
vAddressFk,
vNotes,
vClientFk,
vCompanyFk,
vAgencyModeFk,
vIsTaxDataChecked
FROM `order` o
JOIN vn.address a ON a.id = o.address_id JOIN vn.address a ON a.id = o.address_id
JOIN vn.client c ON c.id = a.clientFk JOIN vn.client c ON c.id = a.clientFk
WHERE o.id = vSelf; WHERE o.id = vSelf;
-- Verifica si el cliente tiene los datos comprobados -- Verifica si el cliente tiene los datos comprobados
IF NOT vIsTaxDataChecked THEN IF NOT vIsTaxDataChecked THEN
CALL util.throw ('clientNotVerified'); CALL util.throw('clientNotVerified');
END IF; END IF;
-- Carga las fechas de salida de cada almacen -- Carga las fechas de salida de cada almacen
CALL vn.zone_getShipped (vDelivery, vAddress, vAgencyModeId, FALSE); CALL vn.zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, FALSE);
-- Trabajador que realiza la accion -- Trabajador que realiza la accion
IF vUserId IS NULL THEN IF vUserFk IS NULL THEN
SELECT employeeFk INTO vUserId FROM orderConfig; SELECT employeeFk INTO vUserFk FROM orderConfig;
END IF; END IF;
START TRANSACTION; START TRANSACTION;
@ -89,207 +102,188 @@ BEGIN
CALL order_checkEditable(vSelf); CALL order_checkEditable(vSelf);
-- Check order is not empty -- Check order is not empty
SELECT COUNT(*) > 0 INTO vHasRows
FROM orderRow
WHERE orderFk = vSelf
AND amount > 0;
SELECT COUNT(*) > 0 INTO vOk IF NOT vHasRows THEN
FROM order_row WHERE order_id = vSelf AND amount > 0; CALL util.throw('ORDER_EMPTY');
IF NOT vOk THEN
CALL util.throw ('ORDER_EMPTY');
END IF; END IF;
-- Crea los tickets del pedido -- Crea los tickets del pedido
OPEN vDates;
OPEN cDates; lDates: LOOP
SET vTicketFk = NULL;
lDates:
LOOP
SET vTicket = NULL;
SET vDone = FALSE; SET vDone = FALSE;
FETCH cDates INTO vShipment, vWarehouse; FETCH vDates INTO vShipment, vWarehouseFk;
IF vDone THEN IF vDone THEN
LEAVE lDates; LEAVE lDates;
END IF; END IF;
-- Busca un ticket existente que coincida con los parametros SET vShipmentDayEnd = util.dayEnd(vShipment);
WITH tPrevia AS
(SELECT DISTINCT s.ticketFk -- Busca un ticket libre disponible
WITH tPrevia AS (
SELECT DISTINCT s.ticketFk
FROM vn.sale s FROM vn.sale s
JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.ticket t ON t.id = s.ticketFk
WHERE t.shipped BETWEEN vShipment AND util.dayend(vShipment) WHERE t.shipped BETWEEN vShipment AND vShipmentDayEnd
) )
SELECT t.id INTO vTicket SELECT t.id INTO vTicketFk
FROM vn.ticket t FROM vn.ticket t
JOIN vn.alertLevel al ON al.code = 'FREE' JOIN vn.alertLevel al ON al.code = 'FREE'
LEFT JOIN tPrevia tp ON tp.ticketFk = t.id LEFT JOIN tPrevia tp ON tp.ticketFk = t.id
LEFT JOIN vn.ticketState tls on tls.ticketFk = t.id LEFT JOIN vn.ticketState tls ON tls.ticketFk = t.id
JOIN hedera.`order` o JOIN hedera.`order` o ON o.address_id = t.addressFk
ON o.address_id = t.addressFk AND t.shipped BETWEEN vShipment AND vShipmentDayEnd
AND vWarehouse = t.warehouseFk AND t.warehouseFk = vWarehouseFk
AND o.date_send = t.landed AND o.date_send = t.landed
AND DATE(t.shipped) = vShipment
WHERE o.id = vSelf WHERE o.id = vSelf
AND t.refFk IS NULL AND t.refFk IS NULL
AND tp.ticketFk IS NULL AND tp.ticketFk IS NULL
AND (tls.alertLevel IS NULL OR tls.alertLevel = al.id) AND (tls.alertLevel IS NULL OR tls.alertLevel = al.id)
LIMIT 1; LIMIT 1;
-- Comprobamos si hay un ticket de previa disponible
IF vTicketFk IS NULL THEN
WITH tItemPackingTypeOrder AS (
SELECT GROUP_CONCAT(
DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk
) distinctItemPackingTypes,
o.address_id
FROM vn.item i
JOIN hedera.orderRow oro ON oro.itemFk = i.id
JOIN hedera.`order` o ON o.id = oro.orderFk
WHERE oro.orderFk = vSelf
),
tItemPackingTypeTicket AS (
SELECT t.id,
GROUP_CONCAT(
DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk
) distinctItemPackingTypes
FROM vn.ticket t
JOIN vn.ticketState tls ON tls.ticketFk = t.id
JOIN vn.alertLevel al ON al.id = tls.alertLevel
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.item i ON i.id = s.itemFk
JOIN tItemPackingTypeOrder ipto
WHERE t.shipped BETWEEN vShipment AND vShipmentDayEnd
AND t.refFk IS NULL
AND t.warehouseFk = vWarehouseFk
AND t.addressFk = ipto.address_id
AND al.code = 'ON_PREVIOUS'
GROUP BY t.id
)
SELECT iptt.id INTO vTicketFk
FROM tItemPackingTypeTicket iptt
JOIN tItemPackingTypeOrder ipto
WHERE INSTR(iptt.distinctItemPackingTypes, ipto.distinctItemPackingTypes)
LIMIT 1;
END IF;
-- Crea el ticket en el caso de no existir uno adecuado -- Crea el ticket en el caso de no existir uno adecuado
IF vTicket IS NULL IF vTicketFk IS NULL THEN
THEN
SET vShipment = IFNULL(vShipment, util.VN_CURDATE()); SET vShipment = IFNULL(vShipment, util.VN_CURDATE());
CALL vn.ticket_add( CALL vn.ticket_add(
vClientId, vClientFk,
vShipment, vShipment,
vWarehouse, vWarehouseFk,
vCompanyId, vCompanyFk,
vAddress, vAddressFk,
vAgencyModeId, vAgencyModeFk,
NULL, NULL,
vDelivery, vLanded,
vUserId, vUserFk,
TRUE, TRUE,
vTicket vTicketFk
); );
ELSE ELSE
INSERT INTO vn.ticketTracking INSERT INTO vn.ticketTracking
SET ticketFk = vTicket, SET ticketFk = vTicketFk,
userFk = vUserId, userFk = vUserFk,
stateFk = TICKET_FREE; stateFk = (SELECT id FROM vn.state WHERE code = 'FREE');
END IF; END IF;
INSERT IGNORE INTO vn.orderTicket INSERT IGNORE INTO vn.orderTicket
SET orderFk = vSelf, SET orderFk = vSelf,
ticketFk = vTicket; ticketFk = vTicketFk;
-- Añade las notas -- Añade las notas
IF vNotes IS NOT NULL AND vNotes <> '' THEN
IF vNotes IS NOT NULL AND vNotes != '' INSERT INTO vn.ticketObservation
THEN SET ticketFk = vTicketFk,
INSERT INTO vn.ticketObservation SET observationTypeFk = (SELECT id FROM vn.observationType WHERE code = 'salesPerson'),
ticketFk = vTicket,
observationTypeFk = 4 /* salesperson */ ,
`description` = vNotes `description` = vNotes
ON DUPLICATE KEY UPDATE ON DUPLICATE KEY UPDATE
`description` = CONCAT(VALUES(`description`),'. ', `description`); `description` = CONCAT(VALUES(`description`),'. ', `description`);
END IF; END IF;
-- Añade los movimientos y sus componentes -- Añade los movimientos y sus componentes
OPEN vRows;
OPEN cRows;
lRows: LOOP lRows: LOOP
SET vSaleFk = NULL;
SET vDone = FALSE; SET vDone = FALSE;
FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate, vIsLogifloraItem; FETCH vRows INTO vRowFk, vItemFk, vConcept, vAmount, vPrice;
IF vDone THEN IF vDone THEN
LEAVE lRows; LEAVE lRows;
END IF; END IF;
SET vSale = NULL; SELECT s.id INTO vSaleFk
SELECT s.id, s.quantity INTO vSale, vOldQuantity
FROM vn.sale s FROM vn.sale s
WHERE ticketFk = vTicket WHERE ticketFk = vTicketFk
AND price = vPrice AND price = vPrice
AND itemFk = vItem AND itemFk = vItemFk
AND discount = 0 AND discount = 0
LIMIT 1; LIMIT 1;
IF vSale THEN IF vSaleFk THEN
UPDATE vn.sale UPDATE vn.sale
SET quantity = quantity + vAmount, SET quantity = quantity + vAmount,
originalQuantity = quantity originalQuantity = quantity
WHERE id = vSale; WHERE id = vSaleFk;
SELECT s.quantity INTO vNewQuantity
FROM vn.sale s
WHERE id = vSale;
ELSE ELSE
-- Obtiene el coste -- Obtiene el coste
SELECT SUM(rc.`price`) valueSum INTO vPriceFixed SELECT SUM(rc.`price`) valueSum INTO vPriceFixed
FROM orderRowComponent rc FROM orderRowComponent rc
JOIN vn.component c ON c.id = rc.componentFk JOIN vn.component c ON c.id = rc.componentFk
JOIN vn.componentType ct ON ct.id = c.typeFk AND ct.isBase JOIN vn.componentType ct ON ct.id = c.typeFk
WHERE rc.rowFk = vRowId; AND ct.isBase
WHERE rc.rowFk = vRowFk;
INSERT INTO vn.sale INSERT INTO vn.sale
SET itemFk = vItem, SET itemFk = vItemFk,
ticketFk = vTicket, ticketFk = vTicketFk,
concept = vConcept, concept = vConcept,
quantity = vAmount, quantity = vAmount,
price = vPrice, price = vPrice,
priceFixed = vPriceFixed, priceFixed = vPriceFixed,
isPriceFixed = TRUE; isPriceFixed = TRUE;
SET vSale = LAST_INSERT_ID(); SET vSaleFk = LAST_INSERT_ID();
INSERT INTO vn.saleComponent INSERT INTO vn.saleComponent (saleFk, componentFk, `value`)
(saleFk, componentFk, `value`) SELECT vSaleFk, rc.componentFk, rc.price
SELECT vSale, rc.componentFk, rc.price
FROM orderRowComponent rc FROM orderRowComponent rc
JOIN vn.component c ON c.id = rc.componentFk JOIN vn.component c ON c.id = rc.componentFk
WHERE rc.rowFk = vRowId WHERE rc.rowFk = vRowFk
GROUP BY vSale, rc.componentFk; GROUP BY vSaleFk, rc.componentFk;
END IF; END IF;
UPDATE order_row SET Id_Movimiento = vSale UPDATE orderRow
WHERE id = vRowId; SET saleFk = vSaleFk
WHERE id = vRowFk;
-- Inserta en putOrder si la compra es de Floramondo
IF vIsLogifloraItem THEN
CALL cache.availableNoRaids_refresh(vCalc,FALSE,vWarehouse,vShipment);
SET @available := 0;
SELECT GREATEST(0,available) INTO @available
FROM cache.availableNoRaids
WHERE calc_id = vCalc
AND item_id = vItem;
UPDATE cache.availableNoRaids
SET available = GREATEST(0,available - vAmount)
WHERE item_id = vItem
AND calc_id = vCalc;
INSERT INTO edi.putOrder (
deliveryInformationID,
supplyResponseId,
quantity ,
EndUserPartyId,
EndUserPartyGLN,
FHAdminNumber,
saleFk
)
SELECT di.ID,
i.supplyResponseFk,
CEIL((vAmount - @available)/ sr.NumberOfItemsPerCask),
o.address_id ,
vClientId,
IFNULL(ca.fhAdminNumber, fhc.defaultAdminNumber),
vSale
FROM edi.deliveryInformation di
JOIN vn.item i ON i.supplyResponseFk = di.supplyResponseID
JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
LEFT JOIN edi.clientFHAdminNumber ca ON ca.clientFk = vClientId
JOIN edi.floraHollandConfig fhc
JOIN hedera.`order` o ON o.id = vSelf
WHERE i.id = vItem
AND di.LatestOrderDateTime > util.VN_NOW()
AND vAmount > @available
LIMIT 1;
END IF;
END LOOP; END LOOP;
CLOSE vRows;
CLOSE cRows;
END LOOP; END LOOP;
CLOSE vDates;
CLOSE cDates; UPDATE `order`
SET confirmed = TRUE,
UPDATE `order` SET confirmed = TRUE, confirm_date = util.VN_NOW() confirm_date = util.VN_NOW()
WHERE id = vSelf; WHERE id = vSelf;
COMMIT; COMMIT;

View File

@ -0,0 +1,12 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `salix`.`ACL_afterDelete`
AFTER DELETE ON `ACL`
FOR EACH ROW
BEGIN
INSERT INTO ACLLog
SET `action` = 'delete',
`changedModel` = 'Acl',
`changedModelId` = OLD.id,
`userFk` = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -0,0 +1,8 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `salix`.`ACL_beforeInsert`
BEFORE INSERT ON `ACL`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -0,0 +1,8 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `salix`.`ACL_beforeUpdate`
BEFORE UPDATE ON `ACL`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -1,13 +1,9 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `srt`.`moving_clean` CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `srt`.`moving_clean`
ON SCHEDULE EVERY 5 MINUTE ON SCHEDULE EVERY 15 MINUTE
STARTS '2022-01-21 00:00:00.000' STARTS '2022-01-21 00:00:00.000'
ON COMPLETION PRESERVE ON COMPLETION PRESERVE
ENABLE ENABLE
COMMENT 'Llama a srt.moving_clean para que elimine y notifique de registr' COMMENT 'Llama a srt.moving_clean para que elimine y notifique de registr'
DO BEGIN DO CALL srt.moving_clean()$$
CALL srt.moving_clean();
END$$
DELIMITER ; DELIMITER ;

View File

@ -3,61 +3,69 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`moving_clean`()
BEGIN BEGIN
/** /**
* Elimina movimientos por inactividad * Elimina movimientos por inactividad
*
*/ */
DECLARE vExpeditionFk INT; DECLARE vExpeditionFk INT;
DECLARE vBufferToFk INT;
DECLARE vBufferFromFk INT; DECLARE vBufferFromFk INT;
DECLARE done BOOL DEFAULT FALSE; DECLARE vStateOutFk INT
DEFAULT (SELECT id FROM expeditionState WHERE `description` = 'OUT');
DECLARE cur CURSOR FOR DECLARE vDone BOOL;
SELECT m.expeditionFk, m.bufferToFk, m.bufferFromFk DECLARE vSorter CURSOR FOR
FROM srt.moving m SELECT m.expeditionFk, m.bufferFromFk
JOIN srt.config c FROM moving m
JOIN (SELECT bufferFk, SUM(isActive) hasBox JOIN (
FROM srt.photocell SELECT bufferFk, SUM(isActive) hasBox
GROUP BY bufferFk) sub ON sub.bufferFk = m.bufferFromFk FROM photocell
WHERE m.created < TIMESTAMPADD(MINUTE, - c.movingMaxLife , util.VN_NOW()) GROUP BY bufferFk
) sub ON sub.bufferFk = m.bufferFromFk
WHERE m.created < (util.VN_NOW() - INTERVAL (SELECT movingMaxLife FROM config) MINUTE)
AND NOT sub.hasBox; AND NOT sub.hasBox;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN cur; DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
bucle: LOOP OPEN vSorter;
l: LOOP
SET vDone = FALSE;
FETCH vSorter INTO vExpeditionFk, vBufferFromFk;
FETCH cur INTO vExpeditionFk, vBufferToFk, vBufferFromFk; IF vDone THEN
LEAVE l;
IF done THEN
LEAVE bucle;
END IF; END IF;
DELETE FROM srt.moving START TRANSACTION;
SELECT id
FROM moving
WHERE expeditionFk = vExpeditionFk
FOR UPDATE;
DELETE FROM moving
WHERE expeditionFk = vExpeditionFk; WHERE expeditionFk = vExpeditionFk;
UPDATE srt.expedition e SELECT id
JOIN srt.expeditionState es ON es.description = 'OUT' FROM expedition
SET WHERE id = vExpeditionFk
bufferFk = NULL, OR (bufferFk = vBufferFromFk AND `position` > 0)
FOR UPDATE;
UPDATE expedition
SET bufferFk = NULL,
`position` = NULL, `position` = NULL,
stateFk = es.id stateFk = vStateOutFk
WHERE e.id = vExpeditionFk; WHERE id = vExpeditionFk;
UPDATE srt.expedition e UPDATE expedition
SET e.`position` = e.`position` - 1 SET `position` = `position` - 1
WHERE e.bufferFk = vBufferFromFk WHERE bufferFk = vBufferFromFk
AND e.`position` > 0; AND `position` > 0;
CALL vn.mail_insert(
'pako@verdnatura.es, carles@verdnatura.es',
NULL,
CONCAT('Moving_clean. Expedition: ', vExpeditionFk, ' estaba parada'),
CONCAT('Expedition: ', vExpeditionFk,' vBufferToFk: ', vBufferToFk)
);
END LOOP bucle;
CLOSE cur;
COMMIT;
END LOOP l;
CLOSE vSorter;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -0,0 +1,12 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `srt`.`buffer_afterDelete`
AFTER DELETE ON `buffer`
FOR EACH ROW
BEGIN
INSERT INTO buffer
SET `action` = 'delete',
`changedModel` = 'Buffer',
`changedModelId` = OLD.id,
`userFk` = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -0,0 +1,8 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `srt`.`buffer_beforeInsert`
BEFORE INSERT ON `buffer`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -0,0 +1,8 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `srt`.`buffer_beforeUpdate`
BEFORE UPDATE ON `buffer`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -0,0 +1,12 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `srt`.`config_afterDelete`
AFTER DELETE ON `config`
FOR EACH ROW
BEGIN
INSERT INTO config
SET `action` = 'delete',
`changedModel` = 'Config',
`changedModelId` = OLD.id,
`userFk` = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -0,0 +1,8 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `srt`.`config_beforeInsert`
BEFORE INSERT ON `config`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -0,0 +1,8 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `srt`.`config_beforeUpdate`
BEFORE UPDATE ON `config`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -1,26 +1,32 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceSerial`(vClientFk INT, vCompanyFk INT, vType CHAR(1)) CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceSerial`(vClientFk INT, vCompanyFk INT, vType CHAR(15))
RETURNS char(1) CHARSET utf8mb3 COLLATE utf8mb3_general_ci RETURNS char(2) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
DETERMINISTIC DETERMINISTIC
BEGIN BEGIN
/** /**
* Obtiene la serie de de una factura * Obtiene la serie de una factura
* dependiendo del area del cliente. * dependiendo del area del cliente.
* *
* @param vClientFk Id del cliente * @param vClientFk Id del cliente
* @param vCompanyFk Id de la empresa * @param vCompanyFk Id de la empresa
* @param vType Tipo de factura ["R", "M", "G"] * @param vType Tipo de factura ['global','multiple','quick']
* @return Serie de la factura * @return vSerie de la factura
*/ */
DECLARE vTaxArea VARCHAR(25); DECLARE vTaxArea VARCHAR(25) COLLATE utf8mb3_general_ci;
DECLARE vSerie CHAR(1); DECLARE vSerie CHAR(2);
IF (SELECT hasInvoiceSimplified FROM client WHERE id = vClientFk) THEN IF (SELECT hasInvoiceSimplified FROM client WHERE id = vClientFk) THEN
RETURN 'S'; RETURN 'S';
END IF; END IF;
SELECT clientTaxArea(vClientFk, vCompanyFk) INTO vTaxArea; SELECT addressTaxArea(defaultAddressFk, vCompanyFk) INTO vTaxArea
SELECT invoiceSerialArea(vType,vTaxArea) INTO vSerie; FROM client
WHERE id = vClientFk;
SELECT code INTO vSerie
FROM invoiceOutSerial
WHERE `type` = vType AND taxAreaFk = vTaxArea;
RETURN vSerie; RETURN vSerie;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -1,34 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceSerialArea`(vType CHAR(1), vTaxArea VARCHAR(25))
RETURNS char(1) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
DECLARE vSerie CHAR(1);
IF vType = 'R' THEN
SELECT
CASE vTaxArea
WHEN 'CEE' THEN 'H'
WHEN 'WORLD' THEN 'E'
ELSE 'T'
END INTO vSerie;
-- Factura multiple
ELSEIF vType = 'M' THEN
SELECT
CASE vTaxArea
WHEN 'CEE' THEN 'H'
WHEN 'WORLD' THEN 'E'
ELSE 'M'
END INTO vSerie;
-- Factura global
ELSEIF vType = 'G' THEN
SELECT
CASE vTaxArea
WHEN 'CEE' THEN 'V'
WHEN 'WORLD' THEN 'X'
ELSE 'A'
END INTO vSerie;
END IF;
RETURN vSerie;
END$$
DELIMITER ;

View File

@ -2,7 +2,7 @@ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_isTooLittle`( CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_isTooLittle`(
vSelf INT vSelf INT
) )
RETURNS tinyint(1) RETURNS BOOL
READS SQL DATA READS SQL DATA
BEGIN BEGIN
/** /**
@ -11,14 +11,21 @@ BEGIN
* @param vSelf Id ticket * @param vSelf Id ticket
* @return BOOL * @return BOOL
*/ */
DECLARE vIsTooLittle TINYINT(1); DECLARE vIsTooLittle BOOL;
WITH ticketData AS (
SELECT addressFk, DATE(shipped) dated
FROM vn.ticket
WHERE id = vSelf
)
SELECT (SUM(IFNULL(sv.litros, 0)) < vc.minTicketVolume SELECT (SUM(IFNULL(sv.litros, 0)) < vc.minTicketVolume
AND IFNULL(t.totalWithoutVat, 0) < vc.minTicketValue) INTO vIsTooLittle AND SUM(IFNULL(t.totalWithoutVat, 0)) < vc.minTicketValue) INTO vIsTooLittle
FROM ticket t FROM ticketData td
LEFT JOIN saleVolume sv ON sv.ticketFk = t.id JOIN vn.ticket t ON t.addressFk = td.addressFk
JOIN volumeConfig vc LEFT JOIN vn.saleVolume sv ON sv.ticketFk = t.id
WHERE t.id = vSelf; JOIN vn.volumeConfig vc
WHERE t.shipped BETWEEN td.dated AND util.dayEnd(td.dated)
AND ticket_isProblemCalcNeeded(t.id);
RETURN vIsTooLittle; RETURN vIsTooLittle;
END$$ END$$

View File

@ -1,8 +1,8 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`address_updateCoordinates`( CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`address_updateCoordinates`(
vTicketFk INT, vTicketFk INT,
vLongitude INT, vLongitude DECIMAL(11,7),
vLatitude INT) vLatitude DECIMAL(11,7))
BEGIN BEGIN
/** /**
* Actualiza las coordenadas de una dirección. * Actualiza las coordenadas de una dirección.

View File

@ -47,7 +47,7 @@ proc: BEGIN
-- Tabla con el ultimo dia de last_buy para cada producto -- Tabla con el ultimo dia de last_buy para cada producto
-- que hace un replace de la anterior. -- que hace un replace de la anterior.
CALL buyUltimate(vWarehouseShipment, util.VN_CURDATE()); CALL buy_getUltimate (NULL, vWarehouseShipment, util.VN_CURDATE());
INSERT INTO tItemRange INSERT INTO tItemRange
SELECT t.itemFk, tr.landed SELECT t.itemFk, tr.landed

View File

@ -5,39 +5,14 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`(
) )
BEGIN BEGIN
/** /**
* Calcula las últimas compras realizadas hasta una fecha * @deprecated Usar buy_getUltimate
* Calcula las últimas compras realizadas hasta una fecha.
* *
* @param vItemFk Id del artículo
* @param vWarehouseFk Id del almacén * @param vWarehouseFk Id del almacén
* @param vDated Compras hasta fecha * @param vDated Compras hasta fecha
* @return tmp.buyUltimate * @return tmp.buyUltimate
*/ */
CALL cache.last_buy_refresh (FALSE); CALL buy_getUltimate(NULL, vWarehouseFk, vDated);
DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate;
CREATE TEMPORARY TABLE tmp.buyUltimate
(PRIMARY KEY (itemFk, warehouseFk),
INDEX(itemFk))
ENGINE = MEMORY
SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing
FROM cache.last_buy
WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL;
IF vDated >= util.VN_CURDATE() THEN
CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated);
REPLACE INTO tmp.buyUltimate
SELECT itemFk, buyFk, warehouseFk, landed landing
FROM tmp.buyUltimateFromInterval
WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
AND landed <= vDated
AND NOT isIgnored;
INSERT IGNORE INTO tmp.buyUltimate
SELECT itemFk, buyFk, warehouseFk, landed landing
FROM tmp.buyUltimateFromInterval
WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
AND landed > vDated
ORDER BY isIgnored = FALSE DESC;
END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -6,6 +6,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInte
) )
BEGIN BEGIN
/** /**
* @deprecated Usar buy_getUltimateFromInterval
* Calcula las últimas compras realizadas * Calcula las últimas compras realizadas
* desde un rango de fechas. * desde un rango de fechas.
* *
@ -14,153 +15,6 @@ BEGIN
* @param vEnded Fecha fin * @param vEnded Fecha fin
* @return tmp.buyUltimateFromInterval * @return tmp.buyUltimateFromInterval
*/ */
IF vEnded IS NULL THEN CALL vn.buy_getUltimateFromInterval(NULL, vWarehouseFk, vStarted, vEnded);
SET vEnded = vStarted;
END IF;
IF vEnded < vStarted THEN
SET vStarted = TIMESTAMPADD(MONTH, -1, vEnded);
END IF;
-- Item
DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval;
CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval
(PRIMARY KEY (itemFk, warehouseFk),
INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk))
ENGINE = MEMORY
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vStarted AND vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.price2 > 0
ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed > vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.price2 > 0
AND NOT b.isIgnored
ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vStarted AND vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.quantity = 0
ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
-- ItemOriginal
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
itemOriginalFk,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vStarted AND vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.price2 > 0
AND NOT b.isIgnored
AND b.quantity > 0
AND itemOriginalFk
ORDER BY t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed > vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.price2 > 0
AND NOT b.isIgnored
AND itemOriginalFk
ORDER BY t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM
(SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vStarted AND vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.quantity = 0
AND itemOriginalFk
ORDER BY t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -0,0 +1,47 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_getUltimate`(
vItemFk INT,
vWarehouseFk SMALLINT,
vDated DATE
)
BEGIN
/**
* Calcula las últimas compras realizadas hasta una fecha.
*
* @param vItemFk Id del artículo
* @param vWarehouseFk Id del almacén
* @param vDated Compras hasta fecha
* @return tmp.buyUltimate
*/
CALL cache.last_buy_refresh(FALSE);
CREATE OR REPLACE TEMPORARY TABLE tmp.buyUltimate
(PRIMARY KEY (itemFk, warehouseFk),
INDEX(itemFk))
ENGINE = MEMORY
SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing
FROM cache.last_buy
WHERE (warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL)
AND (item_id = vItemFk OR vItemFk IS NULL);
IF vDated >= util.VN_CURDATE() THEN
CALL buy_getUltimateFromInterval(vItemFk, vWarehouseFk, util.VN_CURDATE(), vDated);
REPLACE INTO tmp.buyUltimate
SELECT itemFk, buyFk, warehouseFk, landed landing
FROM tmp.buyUltimateFromInterval
WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
AND (itemFk = vItemFk OR vItemFk IS NULL)
AND landed <= vDated
AND NOT isIgnored;
INSERT IGNORE INTO tmp.buyUltimate
SELECT itemFk, buyFk, warehouseFk, landed landing
FROM tmp.buyUltimateFromInterval
WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
AND (itemFk = vItemFk OR vItemFk IS NULL)
AND landed > vDated
ORDER BY isIgnored = FALSE DESC;
END IF;
END$$
DELIMITER ;

View File

@ -0,0 +1,175 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_getUltimateFromInterval`(
vItemFk INT,
vWarehouseFk SMALLINT,
vStarted DATE,
vEnded DATE
)
BEGIN
/**
* Calcula las últimas compras realizadas
* desde un rango de fechas.
*
* @param vItemFk Id del artículo
* @param vWarehouseFk Id del almacén si es NULL se actualizan todos
* @param vStarted Fecha inicial
* @param vEnded Fecha fin
* @return tmp.buyUltimateFromInterval
*/
IF vEnded IS NULL THEN
SET vEnded = vStarted;
END IF;
IF vEnded < vStarted THEN
SET vStarted = vEnded - INTERVAL 1 MONTH;
END IF;
-- Item
CREATE OR REPLACE TEMPORARY TABLE tmp.buyUltimateFromInterval
(PRIMARY KEY (itemFk, warehouseFk),
INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk))
ENGINE = MEMORY
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vStarted AND vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND (b.itemFk = vItemFk OR vItemFk IS NULL)
AND b.price2 > 0
ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed > vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND (b.itemFk = vItemFk OR vItemFk IS NULL)
AND b.price2 > 0
AND NOT b.isIgnored
ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vStarted AND vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND (b.itemFk = vItemFk OR vItemFk IS NULL)
AND b.quantity = 0
ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
-- ItemOriginal
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
itemOriginalFk,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vStarted AND vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND (b.itemFk = vItemFk OR vItemFk IS NULL)
AND b.price2 > 0
AND NOT b.isIgnored
AND b.quantity > 0
AND itemOriginalFk
ORDER BY t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed > vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND (b.itemFk = vItemFk OR vItemFk IS NULL)
AND b.price2 > 0
AND NOT b.isIgnored
AND itemOriginalFk
ORDER BY t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
landed,
isIgnored
FROM
(SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vStarted AND vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND (b.itemFk = vItemFk OR vItemFk IS NULL)
AND b.quantity = 0
AND itemOriginalFk
ORDER BY t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
END$$
DELIMITER ;

View File

@ -1,5 +1,9 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_updateGrouping`(vWarehouseFk INT, vItemFk INT, vGrouping INT) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_updateGrouping`(
vWarehouseFk INT,
vItemFk INT,
vGrouping INT
)
BEGIN BEGIN
/** /**
* Actualiza el grouping de las últimas compras de un artículo * Actualiza el grouping de las últimas compras de un artículo
@ -8,9 +12,9 @@ BEGIN
* @param vItemFk Id del Artículo * @param vItemFk Id del Artículo
* @param vGrouping Cantidad de grouping * @param vGrouping Cantidad de grouping
*/ */
CALL vn.buyUltimate(vWarehouseFk, util.VN_CURDATE()); CALL buy_getUltimate(vItemFk, vWarehouseFk, util.VN_CURDATE());
UPDATE vn.buy b UPDATE buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
SET b.`grouping` = vGrouping SET b.`grouping` = vGrouping
WHERE bu.warehouseFk = vWarehouseFk WHERE bu.warehouseFk = vWarehouseFk

View File

@ -8,7 +8,7 @@ BEGIN
* @param vItemFk id del item * @param vItemFk id del item
* @param vPacking packing a actualizar * @param vPacking packing a actualizar
*/ */
CALL buyUltimate(vWarehouseFk, util.VN_CURDATE()); CALL buy_getUltimate(vItemFk, vWarehouseFk, util.VN_CURDATE());
UPDATE buy b UPDATE buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk JOIN tmp.buyUltimate bu ON b.id = bu.buyFk

View File

@ -29,7 +29,7 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, vShowExpiredZones); CALL zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, vShowExpiredZones);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot( CREATE TEMPORARY TABLE tmp.ticketLot(
@ -72,9 +72,9 @@ BEGIN
LEAVE l; LEAVE l;
END IF; END IF;
CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); CALL `cache`.available_refresh(vAvailableCalc, FALSE, vWarehouseFk, vShipped);
CALL `cache`.availableNoRaids_refresh (vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped); CALL `cache`.availableNoRaids_refresh(vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped);
CALL vn.buyUltimate(vWarehouseFk, vShipped); CALL buy_getUltimate(NULL, vWarehouseFk, vShipped);
INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk) INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk)
SELECT vWarehouseFk, SELECT vWarehouseFk,
@ -86,17 +86,17 @@ BEGIN
LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id
AND anr.calc_id = vAvailableNoRaidsCalc AND anr.calc_id = vAvailableNoRaidsCalc
JOIN tmp.item i ON i.itemFk = a.item_id JOIN tmp.item i ON i.itemFk = a.item_id
JOIN vn.item it ON it.id = i.itemFk JOIN item it ON it.id = i.itemFk
JOIN vn.`zone` z ON z.id = vZoneFk JOIN `zone` z ON z.id = vZoneFk
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id
LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk
LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed
FROM vn.addressFilter af FROM addressFilter af
JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed
FROM vn.address ad FROM address ad
JOIN vn.province p ON p.id = ad.provinceFk JOIN province p ON p.id = ad.provinceFk
WHERE ad.id = vAddressFk WHERE ad.id = vAddressFk
) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk) ) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk)
AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk) AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk)
@ -108,18 +108,18 @@ BEGIN
OR ISNULL(af.afterDated)) OR ISNULL(af.afterDated))
) sub ON sub.isVNHSupplier = v.isVNHSupplier ) sub ON sub.isVNHSupplier = v.isVNHSupplier
AND (sub.isEarlyBird = mp.isEarlyBird OR ISNULL(sub.isEarlyBird)) AND (sub.isEarlyBird = mp.isEarlyBird OR ISNULL(sub.isEarlyBird))
JOIN vn.agencyMode am ON am.id = vAgencyModeFk JOIN agencyMode am ON am.id = vAgencyModeFk
JOIN vn.agency ag ON ag.id = am.agencyFk JOIN agency ag ON ag.id = am.agencyFk
JOIN vn.itemType itt ON itt.id = it.typeFk JOIN itemType itt ON itt.id = it.typeFk
JOIN vn.itemCategory itc on itc.id = itt.categoryFk JOIN itemCategory itc on itc.id = itt.categoryFk
JOIN vn.address ad ON ad.id = vAddressFk JOIN address ad ON ad.id = vAddressFk
LEFT JOIN vn.clientItemType cit LEFT JOIN clientItemType cit
ON cit.clientFk = ad.clientFk ON cit.clientFk = ad.clientFk
AND cit.itemTypeFk = itt.id AND cit.itemTypeFk = itt.id
LEFT JOIN vn.zoneItemType zit LEFT JOIN zoneItemType zit
ON zit.zoneFk = vZoneFk ON zit.zoneFk = vZoneFk
AND zit.itemTypeFk = itt.id AND zit.itemTypeFk = itt.id
LEFT JOIN vn.agencyModeItemType ait LEFT JOIN agencyModeItemType ait
ON ait.agencyModeFk = vAgencyModeFk ON ait.agencyModeFk = vAgencyModeFk
AND ait.itemTypeFk = itt.id AND ait.itemTypeFk = itt.id
WHERE a.calc_id = vAvailableCalc WHERE a.calc_id = vAvailableCalc
@ -133,7 +133,7 @@ BEGIN
DROP TEMPORARY TABLE tmp.buyUltimate; DROP TEMPORARY TABLE tmp.buyUltimate;
CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
INSERT INTO tmp.ticketCalculateItem( INSERT INTO tmp.ticketCalculateItem(
itemFk, itemFk,

View File

@ -19,14 +19,12 @@ BEGIN
DELETE FROM workerActivity WHERE created < v2Years; DELETE FROM workerActivity WHERE created < v2Years;
DELETE FROM ticketParking WHERE created < v2Months; DELETE FROM ticketParking WHERE created < v2Months;
DELETE FROM routesMonitor WHERE dated < v2Months; DELETE FROM routesMonitor WHERE dated < v2Months;
DELETE FROM workerTimeControlLog WHERE created < v2Months;
DELETE FROM `message` WHERE sendDate < v2Months; DELETE FROM `message` WHERE sendDate < v2Months;
DELETE FROM messageInbox WHERE sendDate < v2Months; DELETE FROM messageInbox WHERE sendDate < v2Months;
DELETE FROM messageInbox WHERE sendDate < v2Months; DELETE FROM messageInbox WHERE sendDate < v2Months;
DELETE FROM workerTimeControl WHERE timed < v4Years; DELETE FROM workerTimeControl WHERE timed < v4Years;
DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0; DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0;
DELETE FROM ticketDown WHERE created < util.yesterday(); DELETE FROM ticketDown WHERE created < util.yesterday();
DELETE FROM entryLog WHERE creationDate < v2Months;
DELETE IGNORE FROM expedition WHERE created < v26Months; DELETE IGNORE FROM expedition WHERE created < v26Months;
DELETE cs DELETE cs
FROM sms s FROM sms s
@ -61,11 +59,8 @@ BEGIN
DELETE b FROM buy b DELETE b FROM buy b
JOIN entryConfig e ON e.defaultEntry = b.entryFk JOIN entryConfig e ON e.defaultEntry = b.entryFk
WHERE b.created < v2Months; WHERE b.created < v2Months;
DELETE FROM itemShelvingLog WHERE created < v2Months;
DELETE FROM stockBuyed WHERE creationDate < v2Months; DELETE FROM stockBuyed WHERE creationDate < v2Months;
DELETE FROM itemCleanLog WHERE created < util.VN_NOW() - INTERVAL 1 YEAR;
DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months; DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months;
DELETE FROM ticketLog WHERE creationDate <= v5Years;
-- Equipos duplicados -- Equipos duplicados
DELETE w.* DELETE w.*
FROM workerTeam w FROM workerTeam w
@ -174,7 +169,6 @@ BEGIN
-- Borra los registros de collection y ticketcollection -- Borra los registros de collection y ticketcollection
DELETE FROM collection WHERE created < v2Months; DELETE FROM collection WHERE created < v2Months;
DELETE FROM travelLog WHERE creationDate < v3Months;
CALL shelving_clean(); CALL shelving_clean();

View File

@ -21,6 +21,7 @@ BEGIN
AND a.id IS NULL AND a.id IS NULL
AND u.active AND u.active
AND c.created < util.VN_CURDATE() - INTERVAL vMonths MONTH AND c.created < util.VN_CURDATE() - INTERVAL vMonths MONTH
AND NOT u.role = (SELECT id FROM `role` WHERE name = 'supplier')
AND u.id NOT IN ( AND u.id NOT IN (
SELECT DISTINCT c.id SELECT DISTINCT c.id
FROM client c FROM client c

View File

@ -13,39 +13,42 @@ BEGIN
* @param vCollectionFk Id de colección * @param vCollectionFk Id de colección
*/ */
DECLARE vHasTooMuchCollections BOOL; DECLARE vHasTooMuchCollections BOOL;
DECLARE vItemPackingTypeFk VARCHAR(1); DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vWarehouseFk INT; DECLARE vCollectionWorker INT;
DECLARE vLockName VARCHAR(215); DECLARE vMaxNotAssignedCollectionLifeTime TIME;
DECLARE vLockTime INT DEFAULT 30;
DECLARE vErrorNumber INT;
DECLARE vErrorMsg TEXT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION DECLARE vCollections CURSOR FOR
BEGIN WITH collections AS (
GET DIAGNOSTICS CONDITION 1 SELECT tc.collectionFk,
vErrorNumber = MYSQL_ERRNO, SUM(sv.volume) volume,
vErrorMsg = MESSAGE_TEXT; c.saleTotalCount,
c.itemPackingTypeFk,
CALL util.debugAdd('collection_assign', JSON_OBJECT( c.trainFk,
'errorNumber', vErrorNumber, c.warehouseFk,
'errorMsg', vErrorMsg, c.wagons
'lockName', vLockName, FROM vn.ticketCollection tc
'userFk', vUserFk JOIN vn.collection c ON c.id = tc.collectionFk
)); -- Tmp JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk
WHERE c.workerFk IS NULL
IF vLockName IS NOT NULL THEN AND sv.shipped >= util.VN_CURDATE()
DO RELEASE_LOCK(vLockName); GROUP BY tc.collectionFk
END IF; ) SELECT c.collectionFk
RESIGNAL; FROM collections c
END; JOIN vn.operator o
WHERE o.workerFk = vUserFk
AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL)
AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL)
AND o.numberOfWagons = c.wagons
AND o.trainFk = c.trainFk
AND o.warehouseFk = c.warehouseFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-- Si hay colecciones sin terminar, sale del proceso -- Si hay colecciones sin terminar, sale del proceso
CALL collection_get(vUserFk); CALL collection_get(vUserFk);
SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime
collection_assign_lockname INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime
INTO vHasTooMuchCollections,
vLockName
FROM productionConfig pc FROM productionConfig pc
LEFT JOIN tmp.collection ON TRUE; LEFT JOIN tmp.collection ON TRUE;
@ -55,69 +58,69 @@ BEGIN
CALL util.throw('Hay colecciones pendientes'); CALL util.throw('Hay colecciones pendientes');
END IF; END IF;
SELECT warehouseFk, itemPackingTypeFk
INTO vWarehouseFk, vItemPackingTypeFk
FROM operator
WHERE workerFk = vUserFk;
SET vLockName = CONCAT_WS('/',
vLockName,
vWarehouseFk,
vItemPackingTypeFk
);
IF NOT GET_LOCK(vLockName, vLockTime) THEN
CALL util.throw(CONCAT('Cannot get lock: ', vLockName));
END IF;
-- Se eliminan las colecciones sin asignar que estan obsoletas -- Se eliminan las colecciones sin asignar que estan obsoletas
INSERT INTO ticketTracking(stateFk, ticketFk) INSERT INTO ticketTracking(stateFk, ticketFk)
SELECT s.id, tc.ticketFk SELECT s.id, tc.ticketFk
FROM `collection` c FROM `collection` c
JOIN ticketCollection tc ON tc.collectionFk = c.id JOIN ticketCollection tc ON tc.collectionFk = c.id
JOIN `state` s ON s.code = 'PRINTED_AUTO' JOIN `state` s ON s.code = 'PRINTED_AUTO'
JOIN productionConfig pc
WHERE c.workerFk IS NULL WHERE c.workerFk IS NULL
AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime;
DELETE c.* DELETE FROM `collection`
FROM `collection` c WHERE workerFk IS NULL
JOIN productionConfig pc AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime;
WHERE c.workerFk IS NULL
AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
-- Se añade registro al semillero -- Se añade registro al semillero
INSERT INTO collectionHotbed(userFk)
VALUES(vUserFk); INSERT INTO collectionHotbed(userFk) VALUES(vUserFk);
-- Comprueba si hay colecciones disponibles que se ajustan a su configuracion -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion
SELECT MIN(c.id) INTO vCollectionFk
FROM `collection` c
JOIN operator o
ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL)
AND o.numberOfWagons = c.wagons
AND o.trainFk = c.trainFk
AND o.warehouseFk = c.warehouseFk
AND c.workerFk IS NULL
AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL)
JOIN (
SELECT tc.collectionFk, SUM(sv.volume) volume
FROM ticketCollection tc
JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk
WHERE sv.shipped >= util.VN_CURDATE()
GROUP BY tc.collectionFk
) sub ON sub.collectionFk = c.id
AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL)
WHERE o.workerFk = vUserFk;
IF vCollectionFk IS NULL THEN OPEN vCollections;
CALL collection_new(vUserFk, vCollectionFk); l: LOOP
SET vDone = FALSE;
FETCH vCollections INTO vCollectionFk;
IF vDone THEN
LEAVE l;
END IF; END IF;
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SET vCollectionFk = NULL;
RESIGNAL;
END;
START TRANSACTION;
SELECT workerFk INTO vCollectionWorker
FROM `collection`
WHERE id = vCollectionFk FOR UPDATE;
IF vCollectionWorker IS NULL THEN
UPDATE `collection` UPDATE `collection`
SET workerFk = vUserFk SET workerFk = vUserFk
WHERE id = vCollectionFk; WHERE id = vCollectionFk;
DO RELEASE_LOCK(vLockName); COMMIT;
LEAVE l;
END IF;
ROLLBACK;
END;
END LOOP;
CLOSE vCollections;
IF vCollectionFk IS NULL THEN
CALL collection_new(vUserFk, vCollectionFk);
UPDATE `collection`
SET workerFk = vUserFk
WHERE id = vCollectionFk;
END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -0,0 +1,29 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_mergeSales`(vCollectionFk INT)
BEGIN
DECLARE vDone BOOL;
DECLARE vTicketFk INT;
DECLARE vTickets CURSOR FOR
SELECT ticketFk
FROM ticketCollection
WHERE collectionFk = vCollectionFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
OPEN vTickets;
l: LOOP
SET vDone = FALSE;
FETCH vTickets INTO vTicketFk;
IF vDone THEN
LEAVE l;
END IF;
CALL ticket_mergeSales(vTicketFk);
END LOOP;
CLOSE vTickets;
END$$
DELIMITER ;

View File

@ -1,5 +1,8 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_new`(vUserFk INT, OUT vCollectionFk INT) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_new`(
vUserFk INT,
OUT vCollectionFk INT
)
BEGIN BEGIN
/** /**
* Genera colecciones de tickets sin asignar trabajador. * Genera colecciones de tickets sin asignar trabajador.
@ -9,32 +12,32 @@ BEGIN
DECLARE vWarehouseFk INT; DECLARE vWarehouseFk INT;
DECLARE vWagons INT; DECLARE vWagons INT;
DECLARE vTrainFk INT; DECLARE vTrainFk INT;
DECLARE vLinesLimit INT DEFAULT NULL; DECLARE vLinesLimit INT;
DECLARE vTicketLines INT; DECLARE vTicketLines INT;
DECLARE vVolumeLimit DECIMAL DEFAULT NULL; DECLARE vVolumeLimit DECIMAL;
DECLARE vSizeLimit INT;
DECLARE vTicketVolume DECIMAL; DECLARE vTicketVolume DECIMAL;
DECLARE vMaxTickets INT; DECLARE vMaxTickets INT;
DECLARE vStateFk VARCHAR(45); DECLARE vStateCode VARCHAR(45);
DECLARE vFirstTicketFk INT; DECLARE vFirstTicketFk INT;
DECLARE vHour INT;
DECLARE vMinute INT;
DECLARE vWorkerCode VARCHAR(3); DECLARE vWorkerCode VARCHAR(3);
DECLARE vWagonCounter INT DEFAULT 0; DECLARE vWagonCounter INT DEFAULT 1;
DECLARE vTicketFk INT; DECLARE vTicketFk INT;
DECLARE vItemPackingTypeFk VARCHAR(1); DECLARE vItemPackingTypeFk VARCHAR(1);
DECLARE vHasAssignedTickets BOOLEAN; DECLARE vHasAssignedTickets BOOL;
DECLARE vHasUniqueCollectionTime BOOL; DECLARE vHasUniqueCollectionTime BOOL;
DECLARE vDone INT DEFAULT FALSE; DECLARE vHeight INT;
DECLARE vLockName VARCHAR(215); DECLARE vVolume INT;
DECLARE vLockTime INT DEFAULT 30; DECLARE vLiters INT;
DECLARE vLines INT;
DECLARE vTotalLines INT DEFAULT 0;
DECLARE vTotalVolume INT DEFAULT 0;
DECLARE vFreeWagonFk INT; DECLARE vFreeWagonFk INT;
DECLARE vErrorNumber INT; DECLARE vDone INT DEFAULT FALSE;
DECLARE vErrorMsg TEXT;
DECLARE c1 CURSOR FOR DECLARE vTickets CURSOR FOR
SELECT ticketFk, `lines`, m3 SELECT ticketFk, `lines`, m3
FROM tmp.productionBuffer FROM tmp.productionBuffer
WHERE ticketFk <> vFirstTicketFk
ORDER BY HH, ORDER BY HH,
mm, mm,
productionOrder DESC, productionOrder DESC,
@ -47,26 +50,6 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
vErrorNumber = MYSQL_ERRNO,
vErrorMsg = MESSAGE_TEXT;
CALL util.debugAdd('collection_new', JSON_OBJECT(
'errorNumber', vErrorNumber,
'errorMsg', vErrorMsg,
'lockName', vLockName,
'userFk', vUserFk,
'ticketFk', vTicketFk
)); -- Tmp
IF vLockName IS NOT NULL THEN
DO RELEASE_LOCK(vLockName);
END IF;
RESIGNAL;
END;
SELECT pc.ticketTrolleyMax * o.numberOfWagons, SELECT pc.ticketTrolleyMax * o.numberOfWagons,
pc.hasUniqueCollectionTime, pc.hasUniqueCollectionTime,
w.code, w.code,
@ -77,34 +60,26 @@ BEGIN
o.trainFk, o.trainFk,
o.linesLimit, o.linesLimit,
o.volumeLimit, o.volumeLimit,
pc.collection_new_lockname o.sizeLimit
INTO vMaxTickets, INTO vMaxTickets,
vHasUniqueCollectionTime, vHasUniqueCollectionTime,
vWorkerCode, vWorkerCode,
vWarehouseFk, vWarehouseFk,
vItemPackingTypeFk, vItemPackingTypeFk,
vStateFk, vStateCode,
vWagons, vWagons,
vTrainFk, vTrainFk,
vLinesLimit, vLinesLimit,
vVolumeLimit, vVolumeLimit,
vLockName vSizeLimit
FROM productionConfig pc FROM worker w
JOIN worker w ON w.id = vUserFk JOIN operator o ON o.workerFk = w.id
JOIN state st ON st.`code` = 'ON_PREPARATION' JOIN state st ON st.`code` = 'ON_PREPARATION'
JOIN operator o ON o.workerFk = vUserFk; JOIN productionConfig pc
WHERE w.id = vUserFk;
SET vLockName = CONCAT_WS('/',
vLockName,
vWarehouseFk,
vItemPackingTypeFk
);
IF NOT GET_LOCK(vLockName, vLockTime) THEN
CALL util.throw(CONCAT('Cannot get lock: ', vLockName));
END IF;
-- Se prepara el tren, con tantos vagones como sea necesario. -- Se prepara el tren, con tantos vagones como sea necesario.
CREATE OR REPLACE TEMPORARY TABLE tTrain CREATE OR REPLACE TEMPORARY TABLE tTrain
(wagon INT, (wagon INT,
shelve INT, shelve INT,
@ -115,63 +90,70 @@ BEGIN
PRIMARY KEY(wagon, shelve)) PRIMARY KEY(wagon, shelve))
ENGINE = MEMORY; ENGINE = MEMORY;
WHILE vWagons > vWagonCounter DO INSERT INTO tTrain (wagon, shelve, liters, `lines`, height)
SET vWagonCounter = vWagonCounter + 1; WITH RECURSIVE wagonSequence AS (
SELECT vWagonCounter wagon
INSERT INTO tTrain(wagon, shelve, liters, `lines`, height) UNION ALL
SELECT vWagonCounter, cv.`level` , cv.liters , cv.`lines` , cv.height SELECT wagon + 1 wagon
FROM collectionVolumetry cv FROM wagonSequence
WHERE cv.trainFk = vTrainFk WHERE wagon < vWagonCounter + vWagons -1
)
SELECT ws.wagon, cv.`level`, cv.liters, cv.`lines`, cv.height
FROM wagonSequence ws
JOIN vn.collectionVolumetry cv ON cv.trainFk = vTrainFk
AND cv.itemPackingTypeFk = vItemPackingTypeFk; AND cv.itemPackingTypeFk = vItemPackingTypeFk;
END WHILE;
-- Esto desaparecerá cuando tengamos la table cache.ticket -- Esto desaparecerá cuando tengamos la table cache.ticket
CALL productionControl(vWarehouseFk, 0); CALL productionControl(vWarehouseFk, 0);
ALTER TABLE tmp.productionBuffer ALTER TABLE tmp.productionBuffer
ADD COLUMN liters INT, ADD COLUMN liters INT,
ADD COLUMN height INT; ADD COLUMN height INT;
-- Se obtiene nº de colección.
INSERT INTO collection
SET itemPackingTypeFk = vItemPackingTypeFk,
trainFk = vTrainFk,
wagons = vWagons,
warehouseFk = vWarehouseFk;
SELECT LAST_INSERT_ID() INTO vCollectionFk;
-- Los tickets de recogida en Algemesí sólo se sacan si están asignados. -- Los tickets de recogida en Algemesí sólo se sacan si están asignados.
-- Los pedidos con riesgo no se sacan aunque se asignen. -- Los pedidos con riesgo no se sacan aunque se asignen.
DELETE pb.*
DELETE pb
FROM tmp.productionBuffer pb FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state JOIN state s ON s.id = pb.state
WHERE (pb.agency = 'REC_ALGEMESI' WHERE (pb.agency = 'REC_ALGEMESI'
AND s.code <> 'PICKER_DESIGNED') AND s.code <> 'PICKER_DESIGNED')
OR pb.problem LIKE '%RIESGO%'; OR pb.problem LIKE '%RIESGO%';
-- Comprobamos si hay tickets asignados. En ese caso, nos centramos -- Si hay tickets asignados, nos centramos exclusivamente en esos tickets
-- exclusivamente en esos tickets y los sacamos independientemente -- y los sacamos independientemente de problemas o tamaños
-- de problemas o tamaños
SELECT COUNT(*) INTO vHasAssignedTickets SELECT EXISTS (
SELECT TRUE
FROM tmp.productionBuffer pb FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state JOIN state s ON s.id = pb.state
WHERE s.code = 'PICKER_DESIGNED' WHERE s.code = 'PICKER_DESIGNED'
AND pb.workerCode = vWorkerCode; AND pb.workerCode = vWorkerCode
) INTO vHasAssignedTickets;
-- Se dejan en la tabla tmp.productionBuffer sólo aquellos tickets adecuados -- Se dejan en la tabla tmp.productionBuffer sólo aquellos tickets adecuados
IF vHasAssignedTickets THEN IF vHasAssignedTickets THEN
DELETE pb.* DELETE pb
FROM tmp.productionBuffer pb FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state JOIN state s ON s.id = pb.state
WHERE s.code <> 'PICKER_DESIGNED' WHERE s.code <> 'PICKER_DESIGNED'
OR pb.workerCode <> vWorkerCode; OR pb.workerCode <> vWorkerCode;
ELSE ELSE
DELETE pb.* DELETE pb
FROM tmp.productionBuffer pb FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state JOIN state s ON s.id = pb.state
JOIN agencyMode am ON am.id = pb.agencyModeFk JOIN agencyMode am ON am.id = pb.agencyModeFk
JOIN agency a ON a.id = am.agencyFk JOIN agency a ON a.id = am.agencyFk
LEFT JOIN (
SELECT pb.ticketFk, MAX(i.`size`) maxSize
FROM tmp.productionBuffer pb
JOIN ticket t ON t.id = pb.ticketfk
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
GROUP BY pb.ticketFk
) sub ON sub.ticketFk = pb.ticketFk
JOIN productionConfig pc JOIN productionConfig pc
WHERE pb.shipped <> util.VN_CURDATE() WHERE pb.shipped <> util.VN_CURDATE()
OR (pb.ubicacion IS NULL AND a.isOwn) OR (pb.ubicacion IS NULL AND a.isOwn)
@ -182,22 +164,16 @@ BEGIN
OR (NOT pb.H AND pb.V > 0 AND vItemPackingTypeFk = 'H') OR (NOT pb.H AND pb.V > 0 AND vItemPackingTypeFk = 'H')
OR (NOT pb.V AND vItemPackingTypeFk = 'V') OR (NOT pb.V AND vItemPackingTypeFk = 'V')
OR (pc.isPreviousPreparationRequired AND pb.previousWithoutParking) OR (pc.isPreviousPreparationRequired AND pb.previousWithoutParking)
OR LENGTH(pb.problem) > 0 OR LENGTH(pb.problem)
OR (pb.lines >= vLinesLimit AND vLinesLimit IS NOT NULL) OR pb.lines > vLinesLimit
OR (pb.m3 >= vVolumeLimit AND vVolumeLimit IS NOT NULL); OR pb.m3 > vVolumeLimit
OR sub.maxSize > vSizeLimit;
END IF; END IF;
-- Es importante que el primer ticket se coja en todos los casos -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede
SELECT ticketFk, IF vHasUniqueCollectionTime THEN
HH,
mm, SELECT ticketFk INTO vFirstTicketFk
`lines`,
m3
INTO vFirstTicketFk,
vHour,
vMinute,
vTicketLines,
vTicketVolume
FROM tmp.productionBuffer FROM tmp.productionBuffer
ORDER BY HH, ORDER BY HH,
mm, mm,
@ -209,44 +185,44 @@ BEGIN
ticketFk ticketFk
LIMIT 1; LIMIT 1;
-- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede DELETE pb
IF vHasUniqueCollectionTime THEN FROM tmp.productionBuffer pb
DELETE FROM tmp.productionBuffer JOIN tmp.productionBuffer pb2 ON pb2.ticketFk = vFirstTicketFk
WHERE HH <> vHour AND (pb.HH <> pb2.HH OR pb.mm <> pb2.mm);
OR mm <> vMinute;
END IF; END IF;
SET vTicketFk = vFirstTicketFk; OPEN vTickets;
SET @lines = 0; l: LOOP
SET @volume = 0;
OPEN c1;
read_loop: LOOP
SET vDone = FALSE; SET vDone = FALSE;
FETCH vTickets INTO vTicketFk, vTicketLines, vTicketVolume;
IF vDone THEN
LEAVE l;
END IF;
-- Buscamos un ticket que cumpla con los requisitos en el listado -- Buscamos un ticket que cumpla con los requisitos en el listado
IF ((vTicketLines + @lines) <= vLinesLimit OR vLinesLimit IS NULL)
AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN IF (vLinesLimit IS NULL OR (vTotalLines + vTicketLines) <= vLinesLimit)
AND (vVolumeLimit IS NULL OR (vTotalVolume + vTicketVolume) <= vVolumeLimit) THEN
CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk); CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk);
DROP TEMPORARY TABLE tmp.ticketIPT; DROP TEMPORARY TABLE tmp.ticketIPT;
UPDATE tmp.productionBuffer pb SELECT COUNT(*), SUM(litros), MAX(i.`size`), SUM(sv.volume)
JOIN ( INTO vLines, vLiters, vHeight, vVolume
SELECT SUM(litros) liters,
@lines:= COUNT(*) + @lines,
COUNT(*) `lines`,
MAX(i.`size`) height,
@volume := SUM(sv.volume) + @volume,
SUM(sv.volume) volume
FROM saleVolume sv FROM saleVolume sv
JOIN sale s ON s.id = sv.saleFk JOIN sale s ON s.id = sv.saleFk
JOIN item i ON i.id = s.itemFk JOIN item i ON i.id = s.itemFk
WHERE sv.ticketFk = vTicketFk WHERE sv.ticketFk = vTicketFk;
) sub
SET pb.liters = sub.liters, SET vTotalVolume = vTotalVolume + vVolume,
pb.`lines` = sub.`lines`, vTotalLines = vTotalLines + vLines;
pb.height = sub.height
UPDATE tmp.productionBuffer pb
SET pb.liters = vLiters,
pb.`lines` = vLines,
pb.height = vHeight
WHERE pb.ticketFk = vTicketFk; WHERE pb.ticketFk = vTicketFk;
UPDATE tTrain tt UPDATE tTrain tt
@ -263,17 +239,13 @@ BEGIN
tt.height tt.height
LIMIT 1; LIMIT 1;
-- Si no le encuentra una balda adecuada, intentamos darle un carro entero si queda alguno libre -- Si no le encuentra una balda, intentamos darle un carro entero libre
IF NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN IF NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
SELECT tt.wagon SELECT wagon INTO vFreeWagonFk
INTO vFreeWagonFk
FROM tTrain tt
LEFT JOIN (
SELECT DISTINCT wagon
FROM tTrain FROM tTrain
WHERE ticketFk IS NOT NULL GROUP BY wagon
) nn ON nn.wagon = tt.wagon HAVING SUM(IFNULL(ticketFk, 0)) = 0
WHERE nn.wagon IS NULL
ORDER BY wagon ORDER BY wagon
LIMIT 1; LIMIT 1;
@ -282,38 +254,35 @@ BEGIN
SET ticketFk = vFirstTicketFk SET ticketFk = vFirstTicketFk
WHERE wagon = vFreeWagonFk; WHERE wagon = vFreeWagonFk;
-- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo -- Se anulan el resto de carros libres,
DELETE tt.* -- máximo un carro con pedido excesivo
FROM tTrain tt
LEFT JOIN (
SELECT DISTINCT wagon
FROM tTrain
WHERE ticketFk IS NOT NULL
) nn ON nn.wagon = tt.wagon
WHERE nn.wagon IS NULL;
END IF;
END IF;
FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume; DELETE tt
IF vDone OR NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk IS NULL) THEN FROM tTrain tt
LEAVE read_loop; JOIN (SELECT wagon
FROM tTrain
GROUP BY wagon
HAVING SUM(IFNULL(ticketFk, 0)) = 0
) sub ON sub.wagon = tt.wagon;
END IF; END IF;
ELSE
FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume;
IF vDone THEN
LEAVE read_loop;
END IF; END IF;
END IF; END IF;
END LOOP; END LOOP;
CLOSE c1; CLOSE vTickets;
IF (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN IF (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
UPDATE collection c -- Se obtiene nº de colección
JOIN state st ON st.code = 'ON_PREPARATION'
SET c.stateFk = st.id INSERT INTO collection
WHERE c.id = vCollectionFk; SET itemPackingTypeFk = vItemPackingTypeFk,
trainFk = vTrainFk,
wagons = vWagons,
warehouseFk = vWarehouseFk;
SELECT LAST_INSERT_ID() INTO vCollectionFk;
-- Asigna las bandejas -- Asigna las bandejas
INSERT IGNORE INTO ticketCollection(ticketFk, collectionFk, `level`, wagon, liters) INSERT IGNORE INTO ticketCollection(ticketFk, collectionFk, `level`, wagon, liters)
SELECT tt.ticketFk, vCollectionFk, tt.shelve, tt.wagon, tt.liters SELECT tt.ticketFk, vCollectionFk, tt.shelve, tt.wagon, tt.liters
FROM tTrain tt FROM tTrain tt
@ -321,37 +290,34 @@ BEGIN
ORDER BY tt.wagon, tt.shelve; ORDER BY tt.wagon, tt.shelve;
-- Actualiza el estado de los tickets -- Actualiza el estado de los tickets
CALL collection_setState(vCollectionFk, vStateFk);
CALL collection_setState(vCollectionFk, vStateCode);
-- Aviso para la preparacion previa -- Aviso para la preparacion previa
INSERT INTO ticketDown(ticketFk, collectionFk) INSERT INTO ticketDown(ticketFk, collectionFk)
SELECT tc.ticketFk, tc.collectionFk SELECT tc.ticketFk, tc.collectionFk
FROM ticketCollection tc FROM ticketCollection tc
WHERE tc.collectionFk = vCollectionFk; WHERE tc.collectionFk = vCollectionFk;
CALL sales_mergeByCollection(vCollectionFk); CALL collection_mergeSales(vCollectionFk);
UPDATE `collection` c UPDATE `collection` c
JOIN ( JOIN(
SELECT COUNT(*) saleTotalCount, SELECT COUNT(*) saleTotalCount,
SUM(s.isPicked <> 0) salePickedCount SUM(s.isPicked <> 0) salePickedCount
FROM ticketCollection tc FROM ticketCollection tc
JOIN sale s ON s.ticketFk = tc.ticketFk JOIN sale s ON s.ticketFk = tc.ticketFk
WHERE tc.collectionFk = vCollectionFk WHERE tc.collectionFk = vCollectionFk
AND s.quantity > 0 AND s.quantity > 0
) sub )sub
SET c.saleTotalCount = sub.saleTotalCount, SET c.saleTotalCount = sub.saleTotalCount,
c.salePickedCount = sub.salePickedCount c.salePickedCount = sub.salePickedCount
WHERE c.id = vCollectionFk; WHERE c.id = vCollectionFk;
ELSE ELSE
DELETE FROM `collection`
WHERE id = vCollectionFk;
SET vCollectionFk = NULL; SET vCollectionFk = NULL;
END IF; END IF;
DO RELEASE_LOCK(vLockName);
DROP TEMPORARY TABLE DROP TEMPORARY TABLE
tTrain, tTrain,
tmp.productionBuffer; tmp.productionBuffer;

View File

@ -32,7 +32,7 @@ BEGIN
JOIN duaEntry de ON de.entryFk = e.id JOIN duaEntry de ON de.entryFk = e.id
JOIN invoiceInConfig iic JOIN invoiceInConfig iic
WHERE de.duaFk = vDuaFk WHERE de.duaFk = vDuaFk
AND iidd.dueDated <= util.VN_CURDATE() + INTERVAL iic.dueDateMarginDays DAY; AND iidd.dueDated < util.VN_CURDATE() + INTERVAL iic.dueDateMarginDays DAY;
IF vIncorrectInvoiceInDueDay THEN IF vIncorrectInvoiceInDueDay THEN
CALL util.throw(CONCAT('Incorrect due date, invoice: ', vIncorrectInvoiceInDueDay)); CALL util.throw(CONCAT('Incorrect due date, invoice: ', vIncorrectInvoiceInDueDay));

View File

@ -97,7 +97,7 @@ BEGIN
FROM tmp.itemList; FROM tmp.itemList;
END IF; END IF;
CALL buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded); CALL buy_getUltimateFromInterval(NULL, vWarehouseIn,vInventoryDate, vDateLanded);
CREATE OR REPLACE TEMPORARY TABLE tTransfer CREATE OR REPLACE TEMPORARY TABLE tTransfer
ENGINE = MEMORY ENGINE = MEMORY

View File

@ -15,7 +15,7 @@ BEGIN
DECLARE cur CURSOR FOR DECLARE cur CURSOR FOR
SELECT bb.id buyFk, SELECT bb.id buyFk,
FLOOR(ish.visible / ish.packing) ishStickers, LEAST(bb.stickers, FLOOR(ish.visible / ish.packing)) ishStickers,
bb.stickers buyStickers bb.stickers buyStickers
FROM itemShelving ish FROM itemShelving ish
JOIN (SELECT b.id, b.itemFk, b.stickers JOIN (SELECT b.id, b.itemFk, b.stickers
@ -23,7 +23,6 @@ BEGIN
WHERE b.entryFk = vFromEntryFk WHERE b.entryFk = vFromEntryFk
ORDER BY b.stickers DESC ORDER BY b.stickers DESC
LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
AND bb.stickers >= FLOOR(ish.visible / ish.packing)
WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci
AND NOT ish.isSplit AND NOT ish.isSplit
GROUP BY ish.id; GROUP BY ish.id;
@ -110,7 +109,7 @@ BEGIN
UPDATE itemShelving UPDATE itemShelving
SET isSplit = TRUE SET isSplit = TRUE
WHERE shelvingFk = vShelvingFk; WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci;
END LOOP; END LOOP;
CLOSE cur; CLOSE cur;
END$$ END$$

View File

@ -1,11 +1,18 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionScan_Put`(vPalletFk INT, vExpeditionFk INT) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionScan_Put`(
vPalletFk INT,
vExpeditionFk INT
)
BEGIN BEGIN
IF NOT (SELECT TRUE FROM expedition WHERE id = vExpeditionFk LIMIT 1) THEN
CALL util.throw('Expedition not exists');
END IF;
REPLACE vn.expeditionScan(expeditionFk, palletFk) IF NOT (SELECT TRUE FROM expeditionPallet WHERE id = vPalletFk LIMIT 1) THEN
CALL util.throw('Pallet not exists');
END IF;
REPLACE expeditionScan(expeditionFk, palletFk)
VALUES(vExpeditionFk, vPalletFk); VALUES(vExpeditionFk, vPalletFk);
SELECT LAST_INSERT_ID() INTO vPalletFk;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -16,9 +16,11 @@ BEGIN
DECLARE vHasRepeatedTransactions BOOL; DECLARE vHasRepeatedTransactions BOOL;
SELECT TRUE INTO vHasRepeatedTransactions SELECT TRUE INTO vHasRepeatedTransactions
FROM invoiceInTax FROM invoiceInTax iit
WHERE invoiceInFk = vSelf JOIN invoiceIn ii ON ii.id = iit.invoiceInFk
HAVING COUNT(DISTINCT transactionTypeSageFk) > 1 WHERE ii.id = vSelf
AND ii.serial = 'E'
HAVING COUNT(DISTINCT iit.transactionTypeSageFk) > 1
LIMIT 1; LIMIT 1;
IF vHasRepeatedTransactions THEN IF vHasRepeatedTransactions THEN

View File

@ -97,7 +97,7 @@ BEGIN
AND (vCorrectingSerial = vSerial OR NOT hasAnyNegativeBase()) AND (vCorrectingSerial = vSerial OR NOT hasAnyNegativeBase())
THEN THEN
-- el trigger añade el siguiente Id_Factura correspondiente a la vSerial -- el trigger añade el siguiente ref correspondiente a la vSerial
INSERT INTO invoiceOut( INSERT INTO invoiceOut(
ref, ref,
serial, serial,

View File

@ -0,0 +1,46 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addBySaleGroup`(
vSaleGroupFk INT(11)
)
BEGIN
/**
* Reserva cantidades con ubicaciones para el contenido de una preparación previa
* a través del saleGroup
*
* @param vSaleGroupFk Identificador de saleGroup
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vSaleFk INT;
DECLARE vSectorFk INT;
DECLARE vSales CURSOR FOR
SELECT s.id
FROM saleGroupDetail sgd
JOIN sale s ON sgd.saleFk = s.id
JOIN saleTracking str ON str.saleFk = s.id
JOIN `state` st ON st.id = str.stateFk
AND st.code = 'PREVIOUS_PREPARATION'
LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id
WHERE sgd.saleGroupFk = vSaleGroupFk
AND str.workerFk = account.myUser_getId()
AND iss.id IS NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SELECT sectorFk INTO vSectorFk
FROM operator
WHERE workerFk = account.myUser_getId();
OPEN vSales;
l: LOOP
SET vDone = FALSE;
FETCH vSales INTO vSaleFk;
IF vDone THEN
LEAVE l;
END IF;
CALL itemShelvingSale_addBySale(vSaleFk, vSectorFk);
END LOOP;
CLOSE vSales;
END$$
DELIMITER ;

View File

@ -12,7 +12,7 @@ BEGIN
DECLARE vSaleFk INT; DECLARE vSaleFk INT;
DECLARE vSectorFk INT; DECLARE vSectorFk INT;
DECLARE vSales CURSOR FOR DECLARE vSales CURSOR FOR
SELECT s.id SELECT DISTINCT s.id
FROM sectorCollectionSaleGroup sc FROM sectorCollectionSaleGroup sc
JOIN saleGroupDetail sg ON sg.saleGroupFk = sc.saleGroupFk JOIN saleGroupDetail sg ON sg.saleGroupFk = sc.saleGroupFk
JOIN sale s ON sg.saleFk = s.id JOIN sale s ON sg.saleFk = s.id

View File

@ -30,12 +30,12 @@ BEGIN
FROM itemShelvingSale iss FROM itemShelvingSale iss
JOIN itemShelving ish ON ish.id = iss.itemShelvingFk JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
WHERE iss.itemShelvingFk = vItemShelvingFk WHERE iss.itemShelvingFk = vItemShelvingFk
AND iss.itemFk = vItemFk AND ish.itemFk = vItemFk
AND NOT iss.isPicked AND NOT iss.isPicked
FOR UPDATE; FOR UPDATE;
INSERT INTO itemShelvingSaleReserve (saleFk, vSectorFk) INSERT INTO itemShelvingSaleReserve (saleFk, sectorFk)
SELECT DISTINCT iss.saleFk SELECT DISTINCT iss.saleFk, vSectorFk
FROM itemShelvingSale iss FROM itemShelvingSale iss
JOIN itemShelving ish ON ish.id = iss.itemShelvingFk JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
WHERE iss.itemShelvingFk = vItemShelvingFk WHERE iss.itemShelvingFk = vItemShelvingFk

View File

@ -103,7 +103,7 @@ BEGIN
COMMIT; COMMIT;
IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN
INSERT INTO itemShelvingSaleReserve (saleFk, vSectorFk) INSERT INTO itemShelvingSaleReserve (saleFk, sectorFk)
SELECT vSaleFk, vSectorFk; SELECT vSaleFk, vSectorFk;
CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk, vSectorFk); CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk, vSectorFk);
END IF; END IF;

View File

@ -15,7 +15,7 @@ BEGIN
JOIN ticket t ON t.id = c.ticketFk JOIN ticket t ON t.id = c.ticketFk
WHERE c.id = vClaimFk; WHERE c.id = vClaimFk;
CALL buyUltimate (vWarehouseFk, util.VN_CURDATE()); CALL buy_getUltimate(NULL, vWarehouseFk, util.VN_CURDATE());
INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible) INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible)
SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity AS visible SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity AS visible

View File

@ -16,7 +16,8 @@ BEGIN
ish.id, ish.id,
s.priority, s.priority,
ish.isChecked, ish.isChecked,
ic.url ic.url,
ish.available
FROM itemShelving ish FROM itemShelving ish
JOIN item i ON i.id = ish.itemFk JOIN item i ON i.id = ish.itemFk
JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci

View File

@ -23,7 +23,7 @@ BEGIN
FROM operator FROM operator
WHERE workerFk = account.myUser_getId(); WHERE workerFk = account.myUser_getId();
CALL buyUltimate(vWarehouseFk, util.VN_CURDATE()); CALL buy_getUltimate(vBarcodeItem, vWarehouseFk, util.VN_CURDATE());
SELECT buyFk INTO vBuyFk SELECT buyFk INTO vBuyFk
FROM tmp.buyUltimate FROM tmp.buyUltimate

View File

@ -93,7 +93,7 @@ BEGIN
ORDER BY created DESC ORDER BY created DESC
LIMIT 1; LIMIT 1;
CALL buyUltimate(vWarehouseFk, vCurdate); CALL buy_getUltimate(vSelf, vWarehouseFk, vCurdate);
SELECT b.entryFk, bu.buyFk,IFNULL(b.buyingValue, 0) INTO vLastEntryFk, vLastBuyFk, vBuyingValueOriginal SELECT b.entryFk, bu.buyFk,IFNULL(b.buyingValue, 0) INTO vLastEntryFk, vLastBuyFk, vBuyingValueOriginal
FROM tmp.buyUltimate bu FROM tmp.buyUltimate bu

View File

@ -240,7 +240,7 @@ BEGIN
NULL reference, NULL reference,
NULL entityType, NULL entityType,
NULL entityId, NULL entityId,
'Inventario calculado', 'Inventario calculado' entityName,
@a invalue, @a invalue,
NULL `out`, NULL `out`,
@a balance, @a balance,

View File

@ -1,5 +1,8 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getInfo`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getInfo`(
`vBarcode` VARCHAR(22),
`vWarehouseFk` INT
)
BEGIN BEGIN
/** /**
* Devuelve información relativa al item correspondiente del vBarcode pasado * Devuelve información relativa al item correspondiente del vBarcode pasado
@ -11,12 +14,14 @@ BEGIN
DECLARE vCacheAvailableFk INT; DECLARE vCacheAvailableFk INT;
DECLARE vVisibleItemShelving INT; DECLARE vVisibleItemShelving INT;
DECLARE vItemFk INT; DECLARE vItemFk INT;
DECLARE vDated DATE;
SELECT barcodeToItem(vBarcode), util.VN_CURDATE() INTO vItemFk, vDated;
CALL cache.visible_refresh(vCacheVisibleFk, FALSE, vWarehouseFk); CALL cache.visible_refresh(vCacheVisibleFk, FALSE, vWarehouseFk);
CALL cache.available_refresh(vCacheAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); CALL cache.available_refresh(vCacheAvailableFk, FALSE, vWarehouseFk, vDated);
CALL buyUltimate(vWarehouseFk, util.VN_CURDATE()); CALL buy_getUltimate(vItemFk, vWarehouseFk, vDated);
SELECT barcodeToItem(vBarcode) INTO vItemFk;
SELECT SUM(visible) INTO vVisibleItemShelving SELECT SUM(visible) INTO vVisibleItemShelving
FROM itemShelvingStock FROM itemShelvingStock
WHERE itemFk = vItemFk WHERE itemFk = vItemFk

View File

@ -1,37 +1,40 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getMinacum`(IN vWarehouseFk TINYINT, IN vDatedFrom DATETIME, IN vRange INT, IN vItemFk INT) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getMinacum`(
vWarehouseFk TINYINT,
vDated DATE,
vRange INT,
vItemFk INT
)
BEGIN BEGIN
/** /**
* Cálculo del mínimo acumulado, para un item/almacén especificado, en caso de * Cálculo del mínimo acumulado, para un item/almacén
* NULL para todo. * especificado, en caso de NULL para todos.
* *
* @param vWarehouseFk -> warehouseFk * @param vWarehouseFk Id warehouse
* @param vDatedFrom -> fecha inicio * @param vDated Fecha inicio
* @param vRange -> número de días a considerar * @param vRange Número de días a considerar
* @param vItemFk -> Identificador de item * @param vItemFk Id de artículo
* @return tmp.itemMinacum * @return tmp.itemMinacum
*/ */
DECLARE vDatedTo DATETIME; DECLARE vDatedTo DATETIME DEFAULT util.dayEnd(vDated + INTERVAL vRange DAY);
SET vDatedFrom = TIMESTAMP(DATE(vDatedFrom), '00:00:00'); CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
SET vDatedTo = TIMESTAMP(TIMESTAMPADD(DAY, vRange, vDatedFrom), '23:59:59');
DROP TEMPORARY TABLE IF EXISTS tmp.itemCalc;
CREATE TEMPORARY TABLE tmp.itemCalc
(INDEX (itemFk, warehouseFk)) (INDEX (itemFk, warehouseFk))
ENGINE = MEMORY
SELECT sub.itemFk, SELECT sub.itemFk,
sub.dated, sub.dated,
CAST(SUM(sub.quantity) AS SIGNED) quantity, CAST(SUM(sub.quantity) AS SIGNED) quantity,
sub.warehouseFk sub.warehouseFk
FROM (SELECT s.itemFk, FROM (
SELECT s.itemFk,
DATE(t.shipped) dated, DATE(t.shipped) dated,
-s.quantity quantity, -s.quantity quantity,
t.warehouseFk t.warehouseFk
FROM sale s FROM sale s
JOIN ticket t ON t.id = s.ticketFk JOIN ticket t ON t.id = s.ticketFk
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo WHERE t.shipped BETWEEN vDated AND vDatedTo
AND t.warehouseFk AND t.warehouseFk
AND s.quantity != 0 AND s.quantity <> 0
AND (vItemFk IS NULL OR s.itemFk = vItemFk) AND (vItemFk IS NULL OR s.itemFk = vItemFk)
AND (vWarehouseFk IS NULL OR t.warehouseFk = vWarehouseFk) AND (vWarehouseFk IS NULL OR t.warehouseFk = vWarehouseFk)
UNION ALL UNION ALL
@ -42,10 +45,10 @@ BEGIN
FROM buy b FROM buy b
JOIN entry e ON e.id = b.entryFk JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vDatedFrom AND vDatedTo WHERE t.landed BETWEEN vDated AND vDatedTo
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND !e.isExcludedFromAvailable AND NOT e.isExcludedFromAvailable
AND b.quantity != 0 AND b.quantity <> 0
AND (vItemFk IS NULL OR b.itemFk = vItemFk) AND (vItemFk IS NULL OR b.itemFk = vItemFk)
UNION ALL UNION ALL
SELECT b.itemFk, SELECT b.itemFk,
@ -55,28 +58,45 @@ BEGIN
FROM buy b FROM buy b
JOIN entry e ON e.id = b.entryFk JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk JOIN travel t ON t.id = e.travelFk
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo WHERE t.shipped BETWEEN vDated AND vDatedTo
AND (vWarehouseFk IS NULL OR t.warehouseOutFk = vWarehouseFk) AND (vWarehouseFk IS NULL OR t.warehouseOutFk = vWarehouseFk)
AND !e.isExcludedFromAvailable AND NOT e.isExcludedFromAvailable
AND b.quantity != 0 AND b.quantity <> 0
AND (vItemFk IS NULL OR b.itemFk = vItemFk) AND (vItemFk IS NULL OR b.itemFk = vItemFk)
AND !e.isRaid AND NOT e.isRaid
UNION ALL
SELECT r.itemFk,
r.shipment,
-r.amount,
r.warehouseFk
FROM hedera.orderRow r
JOIN hedera.`order` o ON o.id = r.orderFk
JOIN client c ON c.id = o.customer_id
WHERE r.shipment BETWEEN vDated AND vDatedTo
AND (vWarehouseFk IS NULL OR r.warehouseFk = vWarehouseFk)
AND r.created >= (
SELECT util.VN_NOW() - INTERVAL TIME_TO_SEC(reserveTime) SECOND
FROM hedera.orderConfig
)
AND NOT o.confirmed
AND (vItemFk IS NULL OR r.itemFk = vItemFk)
AND r.amount <> 0
) sub ) sub
GROUP BY sub.itemFk, sub.warehouseFk, sub.dated; GROUP BY sub.itemFk, sub.warehouseFk, sub.dated;
CALL item_getAtp(vDatedFrom); CALL item_getAtp(vDated);
DROP TEMPORARY TABLE tmp.itemCalc;
DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum; CREATE OR REPLACE TEMPORARY TABLE tmp.itemMinacum
CREATE TEMPORARY TABLE tmp.itemMinacum
(INDEX(itemFk)) (INDEX(itemFk))
ENGINE = MEMORY ENGINE = MEMORY
SELECT i.itemFk, SELECT itemFk,
i.warehouseFk, warehouseFk,
i.quantity amount quantity amount
FROM tmp.itemAtp i FROM tmp.itemAtp
HAVING amount != 0; WHERE quantity <> 0;
DROP TEMPORARY TABLE tmp.itemAtp; DROP TEMPORARY TABLE
tmp.itemAtp,
tmp.itemCalc;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -13,7 +13,7 @@ BEGIN
*/ */
ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT; ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT;
CALL buyUltimate(vWarehouseFk, vDate); CALL buy_getUltimate (NULL, vWarehouseFk, vDate);
CREATE OR REPLACE TEMPORARY TABLE tmp CREATE OR REPLACE TEMPORARY TABLE tmp
(KEY (itemFk)) (KEY (itemFk))

View File

@ -204,7 +204,7 @@ BEGIN
AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL) AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity); ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity);
CALL buyUltimate(NULL, vDateDayEnd); CALL buy_getUltimate (NULL, NULL, vDateDayEnd);
DELETE FROM tInventory WHERE quantity IS NULL OR NOT quantity; DELETE FROM tInventory WHERE quantity IS NULL OR NOT quantity;

View File

@ -15,11 +15,6 @@ proc: BEGIN
DECLARE vEndingDate DATETIME; DECLARE vEndingDate DATETIME;
DECLARE vIsTodayRelative BOOLEAN; DECLARE vIsTodayRelative BOOLEAN;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
RESIGNAL;
END;
SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY
INTO vEndingDate INTO vEndingDate
FROM productionConfig; FROM productionConfig;
@ -273,7 +268,6 @@ proc: BEGIN
DROP TEMPORARY TABLE DROP TEMPORARY TABLE
tmp.productionTicket, tmp.productionTicket,
tmp.ticket, tmp.ticket,
tmp.risk,
tmp.ticket_problems, tmp.ticket_problems,
tmp.ticketWithPrevia, tmp.ticketWithPrevia,
tItemShelvingStock, tItemShelvingStock,

View File

@ -1,11 +1,13 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_getProblems`(IN vIsTodayRelative tinyint(1)) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_getProblems`(
vIsTodayRelative tinyint(1)
)
BEGIN BEGIN
/** /**
* Calcula los problemas de cada venta para un conjunto de tickets. * Calcula los problemas de cada venta para un conjunto de tickets.
* *
* @param vIsTodayRelative Indica si se calcula el disponible como si todo saliera hoy * @param vIsTodayRelative Indica si se calcula el disponible como si todo saliera hoy
* @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular * @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Tickets a calcular
* @return tmp.sale_problems * @return tmp.sale_problems
*/ */
DECLARE vWarehouseFk INT; DECLARE vWarehouseFk INT;
@ -13,13 +15,11 @@ BEGIN
DECLARE vAvailableCache INT; DECLARE vAvailableCache INT;
DECLARE vVisibleCache INT; DECLARE vVisibleCache INT;
DECLARE vDone BOOL; DECLARE vDone BOOL;
DECLARE vComponentCount INT;
DECLARE vCursor CURSOR FOR DECLARE vCursor CURSOR FOR
SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, util.VN_CURDATE(), DATE(tt.shipped)) SELECT DISTINCT warehouseFk, IF(vIsTodayRelative, util.VN_CURDATE(), DATE(shipped))
FROM tmp.sale_getProblems tt FROM tmp.sale_getProblems
WHERE DATE(tt.shipped) BETWEEN util.VN_CURDATE() WHERE shipped BETWEEN util.VN_CURDATE()
AND util.VN_CURDATE() + INTERVAL IF(vIsTodayRelative, 9.9, 1.9) DAY; AND util.dayEnd(util.VN_CURDATE() + INTERVAL IF(vIsTodayRelative, 9.9, 1.9) DAY);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
@ -48,107 +48,42 @@ BEGIN
PRIMARY KEY (ticketFk, saleFk) PRIMARY KEY (ticketFk, saleFk)
) ENGINE = MEMORY; ) ENGINE = MEMORY;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_list INSERT INTO tmp.sale_problems(ticketFk,
(PRIMARY KEY (ticketFk)) saleFk,
ENGINE = MEMORY isFreezed,
SELECT ticketFk, clientFk risk,
FROM tmp.sale_getProblems; hasHighRisk,
hasTicketRequest,
isTaxDataChecked,
hasComponentLack,
hasRounding,
isTooLittle)
SELECT sgp.ticketFk,
s.id,
IF(FIND_IN_SET('isFreezed', t.problem), TRUE, FALSE) isFreezed,
t.risk,
IF(FIND_IN_SET('hasHighRisk', t.problem), TRUE, FALSE) hasHighRisk,
IF(FIND_IN_SET('hasTicketRequest', t.problem), TRUE, FALSE) hasTicketRequest,
IF(FIND_IN_SET('isTaxDataChecked', t.problem), FALSE, TRUE) isTaxDataChecked,
IF(FIND_IN_SET('hasComponentLack', s.problem), TRUE, FALSE) hasComponentLack,
IF(FIND_IN_SET('hasRounding', s.problem),
LEFT(GROUP_CONCAT('RE: ', i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250),
NULL
) hasRounding,
IF(FIND_IN_SET('isTooLittle', t.problem), TRUE, FALSE) isTooLittle
FROM tmp.sale_getProblems sgp
JOIN ticket t ON t.id = sgp.ticketFk
LEFT JOIN sale s ON s.ticketFk = t.id
LEFT JOIN item i ON i.id = s.itemFk
WHERE s.problem <> '' OR t.problem <> '' OR t.risk
GROUP BY t.id, s.id;
SELECT COUNT(*) INTO vComponentCount
FROM component
WHERE isRequired;
-- Too Little
INSERT INTO tmp.sale_problems(ticketFk, isTooLittle)
SELECT tp.ticketFk, TRUE
FROM tmp.sale_getProblems tp
JOIN ticket t ON t.id = tp.ticketFk
JOIN (
SELECT t.addressFk,
SUM(ROUND(`ic`.`cm3delivery` * `s`.`quantity` / 1000, 0)) litros,
t.totalWithoutVat
FROM tmp.ticket_list tl
JOIN ticket t ON t.id = tl.ticketFk
JOIN sale s ON s.ticketFk = t.id
AND s.quantity > 0
JOIN itemCost ic ON ic.itemFk = s.itemFk
AND ic.warehouseFk = t.warehouseFk
JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
AND zc.dated = util.VN_CURDATE()
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE util.VN_NOW() < (util.VN_CURDATE() + INTERVAL HOUR(zc.`hour`) HOUR) + INTERVAL MINUTE(zc.`hour`) MINUTE
AND dm.code IN ('AGENCY','DELIVERY','PICKUP')
AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight()
GROUP BY t.addressFk
) sub ON sub.addressFk = t.addressFk
JOIN volumeConfig vc
WHERE sub.litros < vc.minTicketVolume
AND sub.totalWithoutVat < vc.minTicketValue;
-- VIP
INSERT INTO tmp.sale_problems(ticketFk, isVip) INSERT INTO tmp.sale_problems(ticketFk, isVip)
SELECT DISTINCT tl.ticketFk, TRUE SELECT sgp.ticketFk, TRUE
FROM tmp.ticket_list tl FROM tmp.sale_getProblems sgp
JOIN client c ON c.id = tl.clientFk JOIN client c ON c.id = sgp.clientFk
WHERE c.businessTypeFk = 'VIP' WHERE c.businessTypeFk = 'VIP'
ON DUPLICATE KEY UPDATE isVip = TRUE; ON DUPLICATE KEY UPDATE isVIP = TRUE;
-- Faltan componentes
INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk)
SELECT ticketFk, (vComponentCount > nComp) hasComponentLack, saleFk
FROM (
SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk
FROM tmp.ticket_list tl
JOIN sale s ON s.ticketFk = tl.ticketFk
LEFT JOIN saleComponent sc ON sc.saleFk = s.id
LEFT JOIN component c ON c.id = sc.componentFk AND c.isRequired
JOIN ticket t ON t.id = tl.ticketFk
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP')
AND s.quantity > 0
GROUP BY s.id
) sub
HAVING hasComponentLack;
-- Cliente congelado
INSERT INTO tmp.sale_problems(ticketFk, isFreezed)
SELECT DISTINCT tl.ticketFk, TRUE
FROM tmp.ticket_list tl
JOIN client c ON c.id = tl.clientFk
WHERE c.isFreezed
ON DUPLICATE KEY UPDATE isFreezed = c.isFreezed;
-- Credit exceeded
CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt
(PRIMARY KEY (clientFk))
ENGINE = MEMORY
SELECT DISTINCT clientFk
FROM tmp.ticket_list;
CALL client_getDebt(util.VN_CURDATE());
INSERT INTO tmp.sale_problems(ticketFk, risk, hasHighRisk)
SELECT DISTINCT tl.ticketFk, r.risk, ((r.risk - cc.riskTolerance) > c.credit + 10)
FROM tmp.ticket_list tl
JOIN ticket t ON t.id = tl.ticketFk
JOIN agencyMode a ON t.agencyModeFk = a.id
JOIN tmp.risk r ON r.clientFk = t.clientFk
JOIN client c ON c.id = t.clientFk
JOIN clientConfig cc
WHERE r.risk > c.credit + 10
AND NOT a.isRiskFree
ON DUPLICATE KEY UPDATE
risk = r.risk, hasHighRisk = ((r.risk - cc.riskTolerance) > c.credit + 10);
-- Antiguo COD 100, son peticiones de compra sin terminar
INSERT INTO tmp.sale_problems(ticketFk, hasTicketRequest)
SELECT DISTINCT tl.ticketFk, TRUE
FROM tmp.ticket_list tl
JOIN ticketRequest tr ON tr.ticketFk = tl.ticketFk
WHERE tr.isOK IS NULL
ON DUPLICATE KEY UPDATE hasTicketRequest = TRUE;
CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock_byWarehouse CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock_byWarehouse
(INDEX (itemFk, warehouseFk)) (INDEX (itemFk, warehouseFk))
@ -160,10 +95,9 @@ BEGIN
JOIN shelving sh ON sh.code = ish.shelvingFk JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk JOIN sector s ON s.id = p.sectorFk
GROUP BY ish.itemFk, GROUP BY ish.itemFk, s.warehouseFk;
s.warehouseFk;
-- Disponible, Faltas, Inventario y Retrasos -- Disponible, faltas, inventario y retrasos
OPEN vCursor; OPEN vCursor;
l: LOOP l: LOOP
SET vDone = FALSE; SET vDone = FALSE;
@ -182,14 +116,14 @@ BEGIN
INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk) INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk)
SELECT ticketFk, problem, saleFk SELECT ticketFk, problem, saleFk
FROM ( FROM (
SELECT tl.ticketFk, SELECT sgp.ticketFk,
LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem, LEFT(CONCAT('F: ', GROUP_CONCAT(i.id, ' ', i.longName, ' ')), 250) problem,
s.id AS saleFk s.id saleFk
FROM tmp.ticket_list tl FROM tmp.sale_getProblems sgp
JOIN ticket t ON t.id = tl.ticketFk JOIN ticket t ON t.id = sgp.ticketFk
JOIN sale s ON s.ticketFk = t.id JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk JOIN item i ON i.id = s.itemFk
JOIN itemType it on it.id = i.typeFk JOIN itemType it ON it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN cache.visible v ON v.item_id = i.id LEFT JOIN cache.visible v ON v.item_id = i.id
AND v.calc_id = vVisibleCache AND v.calc_id = vVisibleCache
@ -197,8 +131,8 @@ BEGIN
AND av.calc_id = vAvailableCache AND av.calc_id = vAvailableCache
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible,0) < s.quantity WHERE IFNULL(v.visible, 0) < s.quantity
AND IFNULL(av.available ,0) < s.quantity AND IFNULL(av.available, 0) < s.quantity
AND IFNULL(issw.visible, 0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity
AND NOT s.isPicked AND NOT s.isPicked
AND NOT s.reserved AND NOT s.reserved
@ -207,27 +141,27 @@ BEGIN
AND NOT i.generic AND NOT i.generic
AND util.VN_CURDATE() = vDate AND util.VN_CURDATE() = vDate
AND t.warehouseFk = vWarehouseFk AND t.warehouseFk = vWarehouseFk
GROUP BY tl.ticketFk) sub GROUP BY sgp.ticketFk) sub
ON DUPLICATE KEY UPDATE itemShortage = sub.problem, saleFk = sub.saleFk; ON DUPLICATE KEY UPDATE itemShortage = sub.problem, saleFk = sub.saleFk;
-- Inventario: Visible suficiente, pero ubicado menor a la cantidad vendida -- Inventario: Visible suficiente, pero ubicado menor a la cantidad vendida
INSERT INTO tmp.sale_problems(ticketFk, itemLost, saleFk) INSERT INTO tmp.sale_problems(ticketFk, itemLost, saleFk)
SELECT ticketFk, problem, saleFk SELECT ticketFk, problem, saleFk
FROM ( FROM (
SELECT tl.ticketFk, SELECT sgp.ticketFk,
LEFT(GROUP_CONCAT('I: ', i.id, ' ', i.longName, ' '), 250) problem, LEFT(GROUP_CONCAT('I: ', i.id, ' ', i.longName, ' '), 250) problem,
s.id saleFk s.id saleFk
FROM tmp.ticket_list tl FROM tmp.sale_getProblems sgp
JOIN ticket t ON t.id = tl.ticketFk JOIN ticket t ON t.id = sgp.ticketFk
JOIN sale s ON s.ticketFk = t.id JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk JOIN item i ON i.id = s.itemFk
JOIN itemType it on it.id = i.typeFk JOIN itemType it ON it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN cache.visible v ON v.item_id = s.itemFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk
AND v.calc_id = vVisibleCache AND v.calc_id = vVisibleCache
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible,0) >= s.quantity WHERE IFNULL(v.visible, 0) >= s.quantity
AND IFNULL(issw.visible, 0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity
AND s.quantity > 0 AND s.quantity > 0
AND NOT s.isPicked AND NOT s.isPicked
@ -237,22 +171,22 @@ BEGIN
AND NOT i.generic AND NOT i.generic
AND util.VN_CURDATE() = vDate AND util.VN_CURDATE() = vDate
AND t.warehouseFk = vWarehouseFk AND t.warehouseFk = vWarehouseFk
GROUP BY tl.ticketFk GROUP BY sgp.ticketFk
) sub ) sub
ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk; ON DUPLICATE KEY UPDATE itemLost = sub.problem, saleFk = sub.saleFk;
-- Retraso: Disponible suficiente, pero no visible ni ubicado -- Retraso: Disponible suficiente, pero no visible ni ubicado
INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk) INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk)
SELECT ticketFk, problem, saleFk SELECT ticketFk, problem, saleFk
FROM ( FROM (
SELECT tl.ticketFk, SELECT sgp.ticketFk,
LEFT(GROUP_CONCAT('R: ', i.id, ' ', i.longName, ' '), 250) problem, LEFT(GROUP_CONCAT('R: ', i.id, ' ', i.longName, ' '), 250) problem,
s.id saleFk s.id saleFk
FROM tmp.ticket_list tl FROM tmp.sale_getProblems sgp
JOIN ticket t ON t.id = tl.ticketFk JOIN ticket t ON t.id = sgp.ticketFk
JOIN sale s ON s.ticketFk = t.id JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk JOIN item i ON i.id = s.itemFk
JOIN itemType it on it.id = i.typeFk JOIN itemType it ON it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN cache.visible v ON v.item_id = s.itemFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk
AND v.calc_id = vVisibleCache AND v.calc_id = vVisibleCache
@ -271,42 +205,27 @@ BEGIN
AND NOT i.generic AND NOT i.generic
AND util.VN_CURDATE() = vDate AND util.VN_CURDATE() = vDate
AND t.warehouseFk = vWarehouseFk AND t.warehouseFk = vWarehouseFk
GROUP BY tl.ticketFk GROUP BY sgp.ticketFk
) sub ) sub
ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk; ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk;
-- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra
CALL buyUltimate(vWarehouseFk, vDate);
INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk)
SELECT ticketFk, problem ,saleFk
FROM (
SELECT tl.ticketFk,
s.id saleFk,
LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem
FROM tmp.ticket_list tl
JOIN ticket t ON t.id = tl.ticketFk
AND t.warehouseFk = vWarehouseFk
JOIN sale s ON s.ticketFk = tl.ticketFk
JOIN item i ON i.id = s.itemFk
JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
JOIN buy b ON b.id = bu.buyFk
WHERE MOD(s.quantity, b.`grouping`)
GROUP BY tl.ticketFk
)sub
ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk;
END LOOP; END LOOP;
CLOSE vCursor; CLOSE vCursor;
INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked) INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk)
SELECT DISTINCT tl.ticketFk, FALSE SELECT ticketFk, problem, saleFk
FROM tmp.ticket_list tl FROM (
JOIN client c ON c.id = tl.clientFk SELECT sgp.ticketFk,
WHERE NOT c.isTaxDataChecked s.id saleFk,
ON DUPLICATE KEY UPDATE isTaxDataChecked = FALSE; LEFT(GROUP_CONCAT('RE: ', i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem
FROM tmp.sale_getProblems sgp
JOIN ticket t ON t.id = sgp.ticketFk
JOIN sale s ON s.ticketFk = sgp.ticketFk
JOIN item i ON i.id = s.itemFk
WHERE FIND_IN_SET('hasRounding', s.problem)
GROUP BY sgp.ticketFk
) sub
ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk;
DROP TEMPORARY TABLE DROP TEMPORARY TABLE tItemShelvingStock_byWarehouse;
tmp.clientGetDebt,
tmp.ticket_list,
tItemShelvingStock_byWarehouse;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -7,8 +7,7 @@ BEGIN
* *
* @return Problems result * @return Problems result
*/ */
DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems; CREATE OR REPLACE TEMPORARY TABLE tmp.sale_getProblems
CREATE TEMPORARY TABLE tmp.sale_getProblems
(INDEX (ticketFk)) (INDEX (ticketFk))
ENGINE = MEMORY ENGINE = MEMORY
SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped

View File

@ -78,7 +78,7 @@ proc: BEGIN
DROP TEMPORARY TABLE tmp.zoneGetLanded; DROP TEMPORARY TABLE tmp.zoneGetLanded;
-- rellena la tabla buyUltimate con la ultima compra -- rellena la tabla buyUltimate con la ultima compra
CALL buyUltimate (vWarehouseFk, vShipped); CALL buy_getUltimate(NULL, vWarehouseFk, vShipped);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(PRIMARY KEY (saleFk)) ENGINE = MEMORY (PRIMARY KEY (saleFk)) ENGINE = MEMORY

View File

@ -53,7 +53,7 @@ BEGIN
JOIN ticket t ON t.id = s.ticketFk JOIN ticket t ON t.id = s.ticketFk
WHERE s.id = vSaleFk; WHERE s.id = vSaleFk;
CALL buyUltimate(vWarehouseFk, vDate); CALL buy_getUltimate(vNewItemFk, vWarehouseFk, vDate);
SELECT `grouping`, groupingMode, packing SELECT `grouping`, groupingMode, packing
INTO vGrouping,vGroupingMode,vPacking INTO vGrouping,vGroupingMode,vPacking
@ -61,6 +61,8 @@ BEGIN
JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk
WHERE tmp.itemFk = vNewItemFk AND tmp.WarehouseFk = vWarehouseFk; WHERE tmp.itemFk = vNewItemFk AND tmp.WarehouseFk = vWarehouseFk;
DROP TEMPORARY TABLE tmp.buyUltimate;
IF vGroupingMode = 'packing' AND vPacking > 0 THEN IF vGroupingMode = 'packing' AND vPacking > 0 THEN
SET vRoundQuantity = vPacking; SET vRoundQuantity = vPacking;
END IF; END IF;

View File

@ -11,24 +11,29 @@ BEGIN
*/ */
DECLARE vSaleFk INT; DECLARE vSaleFk INT;
DECLARE vHasProblem INT; DECLARE vHasProblem INT;
DECLARE vIsProblemCalcNeeded BOOL;
DECLARE vDone BOOL; DECLARE vDone BOOL;
DECLARE vSaleList CURSOR FOR SELECT saleFk, hasProblem FROM tmp.sale; DECLARE vSaleList CURSOR FOR
SELECT saleFk, hasProblem, isProblemCalcNeeded
FROM tmp.sale;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vSaleList; OPEN vSaleList;
l: LOOP l: LOOP
SET vDone = FALSE; SET vDone = FALSE;
FETCH vSaleList INTO vSaleFk, vHasProblem; FETCH vSaleList INTO vSaleFk, vHasProblem, vIsProblemCalcNeeded;
IF vDone THEN IF vDone THEN
LEAVE l; LEAVE l;
END IF; END IF;
UPDATE sale UPDATE sale
SET problem = CONCAT( SET problem = IF (vIsProblemCalcNeeded,
CONCAT(
IF(vHasProblem, IF(vHasProblem,
CONCAT(problem, ',', vProblemCode), CONCAT(problem, ',', vProblemCode),
REPLACE(problem, vProblemCode , ''))) REPLACE(problem, vProblemCode , ''))),
NULL)
WHERE id = vSaleFk; WHERE id = vSaleFk;
END LOOP; END LOOP;
CLOSE vSaleList; CLOSE vSaleList;

View File

@ -14,7 +14,7 @@ BEGIN
ENGINE = MEMORY ENGINE = MEMORY
SELECT vSelf saleFk, SELECT vSelf saleFk,
sale_hasComponentLack(vSelf) hasProblem, sale_hasComponentLack(vSelf) hasProblem,
ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded (ticket_isProblemCalcNeeded(ticketFk) AND quantity > 0) isProblemCalcNeeded
FROM sale FROM sale
WHERE id = vSelf; WHERE id = vSelf;

View File

@ -14,9 +14,9 @@ BEGIN
ENGINE = MEMORY ENGINE = MEMORY
SELECT saleFk, SELECT saleFk,
sale_hasComponentLack(saleFk) hasProblem, sale_hasComponentLack(saleFk) hasProblem,
ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded (ticket_isProblemCalcNeeded(ticketFk) AND quantity > 0) isProblemCalcNeeded
FROM ( FROM (
SELECT s.id saleFk, s.ticketFk SELECT s.id saleFk, s.ticketFk, s.quantity
FROM ticket t FROM ticket t
JOIN sale s ON s.ticketFk = t.id JOIN sale s ON s.ticketFk = t.id
LEFT JOIN saleComponent sc ON sc.saleFk = s.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id

View File

@ -19,7 +19,7 @@ BEGIN
JOIN ticket t ON t.id = s.ticketFk JOIN ticket t ON t.id = s.ticketFk
WHERE s.id = vSelf; WHERE s.id = vSelf;
CALL buyUltimate(vWarehouseFk, vShipped); CALL buy_getUltimate(vItemFk, vWarehouseFk, vShipped);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale CREATE OR REPLACE TEMPORARY TABLE tmp.sale
SELECT vSelf saleFk, SELECT vSelf saleFk,

View File

@ -1,41 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sales_merge`(vTicketFk INT)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve
(PRIMARY KEY (id))
ENGINE = MEMORY
SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity
FROM sale s
JOIN item i ON i.id = s.itemFk
JOIN itemType it ON it.id = i.typeFk
WHERE s.ticketFk = vTicketFk
AND it.isMergeable
GROUP BY s.itemFk, s.price, s.discount;
START TRANSACTION;
UPDATE sale s
JOIN tSalesToPreserve stp ON stp.id = s.id
SET s.quantity = newQuantity
WHERE s.ticketFk = vTicketFk;
DELETE s.*
FROM sale s
LEFT JOIN tSalesToPreserve stp ON stp.id = s.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it ON it.id = i.typeFk
WHERE s.ticketFk = vTicketFk
AND stp.id IS NULL
AND it.isMergeable;
COMMIT;
DROP TEMPORARY TABLE tSalesToPreserve;
END$$
DELIMITER ;

View File

@ -26,7 +26,7 @@ BEGIN
LEAVE myLoop; LEAVE myLoop;
END IF; END IF;
CALL vn.sales_merge(vTicketFk); CALL ticket_mergeSales(vTicketFk);
END LOOP; END LOOP;

View File

@ -36,6 +36,6 @@ BEGIN
WHERE warehouse_id = vAuctionWarehouseFk WHERE warehouse_id = vAuctionWarehouseFk
ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity); ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity);
CALL buyUltimate(vAuctionWarehouseFk, vDated); CALL buy_getUltimate(NULL, vAuctionWarehouseFk, vDated);
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -1,139 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_statement`(
vSupplierFk INT,
vCurrencyFk INT,
vCompanyFk INT,
vOrderBy VARCHAR(15),
vIsConciliated BOOL
)
BEGIN
/**
* Crea un estado de cuenta de proveedores calculando
* los saldos en euros y en la moneda especificada.
*
* @param vSupplierFk Id del proveedor
* @param vCurrencyFk Id de la moneda
* @param vCompanyFk Id de la empresa
* @param vOrderBy Criterio de ordenación
* @param vIsConciliated Indica si está conciliado o no
* @return tmp.supplierStatement
*/
SET @euroBalance:= 0;
SET @currencyBalance:= 0;
CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement
ENGINE = MEMORY
SELECT *,
@euroBalance:= ROUND(
@euroBalance + IFNULL(paymentEuros, 0) -
IFNULL(invoiceEuros, 0), 2
) euroBalance,
@currencyBalance:= ROUND(
@currencyBalance + IFNULL(paymentCurrency, 0) -
IFNULL(invoiceCurrency, 0), 2
) currencyBalance
FROM (
SELECT * FROM
(
SELECT NULL bankFk,
ii.companyFk,
ii.serial,
ii.id,
CASE
WHEN vOrderBy = 'issued' THEN ii.issued
WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried
WHEN vOrderBy = 'booked' THEN ii.booked
WHEN vOrderBy = 'dueDate' THEN iid.dueDated
END dated,
CONCAT('S/Fra ', ii.supplierRef) sref,
IF(ii.currencyFk > 1,
ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3),
NULL
) changeValue,
CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros,
CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency,
NULL paymentEuros,
NULL paymentCurrency,
ii.currencyFk,
ii.isBooked,
c.code,
'invoiceIn' statementType
FROM invoiceIn ii
JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
JOIN currency c ON c.id = ii.currencyFk
WHERE ii.issued > '2014-12-31'
AND ii.supplierFk = vSupplierFk
AND vCurrencyFk IN (ii.currencyFk, 0)
AND vCompanyFk IN (ii.companyFk, 0)
AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated)
GROUP BY iid.id
UNION ALL
SELECT p.bankFk,
p.companyFk,
NULL,
p.id,
CASE
WHEN vOrderBy = 'issued' THEN p.received
WHEN vOrderBy = 'bookEntried' THEN p.received
WHEN vOrderBy = 'booked' THEN p.received
WHEN vOrderBy = 'dueDate' THEN p.dueDated
END,
CONCAT(IFNULL(pm.name, ''),
IF(pn.concept <> '',
CONCAT(' : ', pn.concept),
'')
),
IF(p.currencyFk > 1, p.divisa / p.amount, NULL),
NULL,
NULL,
p.amount,
p.divisa,
p.currencyFk,
p.isConciliated,
c.code,
'payment'
FROM payment p
LEFT JOIN currency c ON c.id = p.currencyFk
LEFT JOIN accounting a ON a.id = p.bankFk
LEFT JOIN payMethod pm ON pm.id = p.payMethodFk
LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id
WHERE p.received > '2014-12-31'
AND p.supplierFk = vSupplierFk
AND vCurrencyFk IN (p.currencyFk, 0)
AND vCompanyFk IN (p.companyFk, 0)
AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated)
UNION ALL
SELECT NULL,
companyFk,
NULL,
se.id,
CASE
WHEN vOrderBy = 'issued' THEN se.dated
WHEN vOrderBy = 'bookEntried' THEN se.dated
WHEN vOrderBy = 'booked' THEN se.dated
WHEN vOrderBy = 'dueDate' THEN se.dueDated
END,
se.description,
1,
amount,
NULL,
NULL,
NULL,
currencyFk,
isConciliated,
c.`code`,
'expense'
FROM supplierExpense se
JOIN currency c ON c.id = se.currencyFk
WHERE se.supplierFk = vSupplierFk
AND vCurrencyFk IN (se.currencyFk,0)
AND vCompanyFk IN (se.companyFk,0)
AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated)
) sub
ORDER BY (dated IS NULL AND NOT isBooked),
dated,
IF(vOrderBy = 'dueDate', id, NULL)
LIMIT 10000000000000000000
) t;
END$$
DELIMITER ;

View File

@ -0,0 +1,166 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE vn.supplier_statementWithEntries(
vSupplierFk INT,
vCurrencyFk INT,
vCompanyFk INT,
vOrderBy VARCHAR(15),
vIsConciliated BOOL,
vHasEntries BOOL
)
BEGIN
/**
* Creates a supplier statement, calculating balances in euros and the specified currency.
*
* @param vSupplierFk Supplier ID
* @param vCurrencyFk Currency ID
* @param vCompanyFk Company ID
* @param vOrderBy Order by criteria
* @param vIsConciliated Indicates whether it is reconciled or not
* @param vHasEntries Indicates if future entries must be shown
* @return tmp.supplierStatement
*/
DECLARE vBalanceStartingDate DATETIME;
SET @euroBalance:= 0;
SET @currencyBalance:= 0;
SELECT balanceStartingDate
INTO vBalanceStartingDate
FROM invoiceInConfig;
CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement
ENGINE = MEMORY
SELECT *,
@euroBalance:= ROUND(
@euroBalance + IFNULL(paymentEuros, 0) -
IFNULL(invoiceEuros, 0), 2
) euroBalance,
@currencyBalance:= ROUND(
@currencyBalance + IFNULL(paymentCurrency, 0) -
IFNULL(invoiceCurrency, 0), 2
) currencyBalance
FROM (
SELECT NULL bankFk,
ii.companyFk,
ii.serial,
ii.id,
CASE
WHEN vOrderBy = 'issued' THEN ii.issued
WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried
WHEN vOrderBy = 'booked' THEN ii.booked
WHEN vOrderBy = 'dueDate' THEN iid.dueDated
END dated,
CONCAT('S/Fra ', ii.supplierRef) sref,
IF(ii.currencyFk > 1,
ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3),
NULL
) changeValue,
CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros,
CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency,
NULL paymentEuros,
NULL paymentCurrency,
ii.currencyFk,
ii.isBooked,
c.code,
'invoiceIn' statementType
FROM invoiceIn ii
JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
JOIN currency c ON c.id = ii.currencyFk
WHERE ii.issued >= vBalanceStartingDate
AND ii.supplierFk = vSupplierFk
AND vCurrencyFk IN (ii.currencyFk, 0)
AND vCompanyFk IN (ii.companyFk, 0)
AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated)
GROUP BY iid.id
UNION ALL
SELECT p.bankFk,
p.companyFk,
NULL,
p.id,
CASE
WHEN vOrderBy = 'issued' THEN p.received
WHEN vOrderBy = 'bookEntried' THEN p.received
WHEN vOrderBy = 'booked' THEN p.received
WHEN vOrderBy = 'dueDate' THEN p.dueDated
END,
CONCAT(IFNULL(pm.name, ''),
IF(pn.concept <> '',
CONCAT(' : ', pn.concept),
'')
),
IF(p.currencyFk > 1, p.divisa / p.amount, NULL),
NULL,
NULL,
p.amount,
p.divisa,
p.currencyFk,
p.isConciliated,
c.code,
'payment'
FROM payment p
LEFT JOIN currency c ON c.id = p.currencyFk
LEFT JOIN accounting a ON a.id = p.bankFk
LEFT JOIN payMethod pm ON pm.id = p.payMethodFk
LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id
WHERE p.received >= vBalanceStartingDate
AND p.supplierFk = vSupplierFk
AND vCurrencyFk IN (p.currencyFk, 0)
AND vCompanyFk IN (p.companyFk, 0)
AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated)
UNION ALL
SELECT NULL,
companyFk,
NULL,
se.id,
CASE
WHEN vOrderBy = 'issued' THEN se.dated
WHEN vOrderBy = 'bookEntried' THEN se.dated
WHEN vOrderBy = 'booked' THEN se.dated
WHEN vOrderBy = 'dueDate' THEN se.dueDated
END,
se.description,
1,
amount,
NULL,
NULL,
NULL,
currencyFk,
isConciliated,
c.`code`,
'expense'
FROM supplierExpense se
JOIN currency c ON c.id = se.currencyFk
WHERE se.supplierFk = vSupplierFk
AND vCurrencyFk IN (se.currencyFk,0)
AND vCompanyFk IN (se.companyFk,0)
AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated)
UNION ALL
SELECT NULL bankFk,
e.companyFk,
'E' serial,
e.invoiceNumber id,
tr.landed dated,
CONCAT('Ent. ',e.id) sref,
1 / ((e.commission/100)+1) changeValue,
e.invoiceAmount * (1 + (e.commission/100)),
e.invoiceAmount,
NULL,
NULL,
e.currencyFk,
FALSE isBooked,
c.code,
'order'
FROM entry e
JOIN travel tr ON tr.id = e.travelFk
JOIN currency c ON c.id = e.currencyFk
WHERE e.supplierFk = vSupplierFk
AND tr.landed >= CURDATE()
AND e.invoiceInFk IS NULL
AND vHasEntries
ORDER BY (dated IS NULL AND NOT isBooked),
dated,
IF(vOrderBy = 'dueDate', id, NULL)
LIMIT 10000000000000000000
) t;
END$$
DELIMITER ;

View File

@ -4,7 +4,6 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_cloneWeekly`
vDateTo DATE vDateTo DATE
) )
BEGIN BEGIN
DECLARE vIsDone BOOL;
DECLARE vLanding DATE; DECLARE vLanding DATE;
DECLARE vShipment DATE; DECLARE vShipment DATE;
DECLARE vWarehouseFk INT; DECLARE vWarehouseFk INT;
@ -15,10 +14,17 @@ BEGIN
DECLARE vAgencyModeFk INT; DECLARE vAgencyModeFk INT;
DECLARE vNewTicket INT; DECLARE vNewTicket INT;
DECLARE vYear INT; DECLARE vYear INT;
DECLARE vSalesPersonFK INT; DECLARE vObservationSalesPersonFk INT
DECLARE vItemPicker INT; DEFAULT (SELECT id FROM observationType WHERE code = 'salesPerson');
DECLARE vObservationItemPickerFk INT
DEFAULT (SELECT id FROM observationType WHERE code = 'itemPicker');
DECLARE vEmail VARCHAR(255);
DECLARE vIsDuplicateMail BOOL;
DECLARE vSubject VARCHAR(100);
DECLARE vMessage TEXT;
DECLARE vDone BOOL;
DECLARE rsTicket CURSOR FOR DECLARE vTickets CURSOR FOR
SELECT tt.ticketFk, SELECT tt.ticketFk,
t.clientFk, t.clientFk,
t.warehouseFk, t.warehouseFk,
@ -31,20 +37,14 @@ BEGIN
JOIN tmp.time ti JOIN tmp.time ti
WHERE WEEKDAY(ti.dated) = tt.weekDay; WHERE WEEKDAY(ti.dated) = tt.weekDay;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
CALL `util`.`time_generate`(vDateFrom,vDateTo); CALL `util`.`time_generate`(vDateFrom, vDateTo);
OPEN rsTicket; OPEN vTickets;
myLoop: LOOP l: LOOP
BEGIN SET vDone = FALSE;
DECLARE vSalesPersonEmail VARCHAR(150); FETCH vTickets INTO
DECLARE vIsDuplicateMail BOOL;
DECLARE vSubject VARCHAR(150);
DECLARE vMessage TEXT;
SET vIsDone = FALSE;
FETCH rsTicket INTO
vTicketFk, vTicketFk,
vClientFk, vClientFk,
vWarehouseFk, vWarehouseFk,
@ -53,11 +53,11 @@ BEGIN
vAgencyModeFk, vAgencyModeFk,
vShipment; vShipment;
IF vIsDone THEN IF vDone THEN
LEAVE myLoop; LEAVE l;
END IF; END IF;
-- busca si el ticket ya ha sido clonado -- Busca si el ticket ya ha sido clonado
IF EXISTS (SELECT TRUE FROM ticket tOrig IF EXISTS (SELECT TRUE FROM ticket tOrig
JOIN sale saleOrig ON tOrig.id = saleOrig.ticketFk JOIN sale saleOrig ON tOrig.id = saleOrig.ticketFk
JOIN saleCloned sc ON sc.saleOriginalFk = saleOrig.id JOIN saleCloned sc ON sc.saleOriginalFk = saleOrig.id
@ -67,7 +67,7 @@ BEGIN
AND tClon.isDeleted = FALSE AND tClon.isDeleted = FALSE
AND DATE(tClon.shipped) = vShipment) AND DATE(tClon.shipped) = vShipment)
THEN THEN
ITERATE myLoop; ITERATE l;
END IF; END IF;
IF vAgencyModeFk IS NULL THEN IF vAgencyModeFk IS NULL THEN
@ -107,15 +107,15 @@ BEGIN
priceFixed, priceFixed,
isPriceFixed) isPriceFixed)
SELECT vNewTicket, SELECT vNewTicket,
saleOrig.itemFk, itemFk,
saleOrig.concept, concept,
saleOrig.quantity, quantity,
saleOrig.price, price,
saleOrig.discount, discount,
saleOrig.priceFixed, priceFixed,
saleOrig.isPriceFixed isPriceFixed
FROM sale saleOrig FROM sale
WHERE saleOrig.ticketFk = vTicketFk; WHERE ticketFk = vTicketFk;
INSERT IGNORE INTO saleCloned(saleOriginalFk, saleClonedFk) INSERT IGNORE INTO saleCloned(saleOriginalFk, saleClonedFk)
SELECT saleOriginal.id, saleClon.id SELECT saleOriginal.id, saleClon.id
@ -152,15 +152,7 @@ BEGIN
attenderFk, attenderFk,
vNewTicket vNewTicket
FROM ticketRequest FROM ticketRequest
WHERE ticketFk =vTicketFk; WHERE ticketFk = vTicketFk;
SELECT id INTO vSalesPersonFK
FROM observationType
WHERE code = 'salesPerson';
SELECT id INTO vItemPicker
FROM observationType
WHERE code = 'itemPicker';
INSERT INTO ticketObservation( INSERT INTO ticketObservation(
ticketFk, ticketFk,
@ -168,7 +160,7 @@ BEGIN
description) description)
VALUES( VALUES(
vNewTicket, vNewTicket,
vSalesPersonFK, vObservationSalesPersonFk,
CONCAT('turno desde ticket: ',vTicketFk)) CONCAT('turno desde ticket: ',vTicketFk))
ON DUPLICATE KEY UPDATE description = ON DUPLICATE KEY UPDATE description =
CONCAT(ticketObservation.description,VALUES(description),' '); CONCAT(ticketObservation.description,VALUES(description),' ');
@ -178,16 +170,17 @@ BEGIN
description) description)
VALUES( VALUES(
vNewTicket, vNewTicket,
vItemPicker, vObservationItemPickerFk,
'ATENCION: Contiene lineas de TURNO') 'ATENCION: Contiene lineas de TURNO')
ON DUPLICATE KEY UPDATE description = ON DUPLICATE KEY UPDATE description =
CONCAT(ticketObservation.description,VALUES(description),' '); CONCAT(ticketObservation.description,VALUES(description),' ');
IF (vLanding IS NULL) THEN IF vLanding IS NULL THEN
SELECT IFNULL(d.notificationEmail, e.email) INTO vEmail
SELECT e.email INTO vSalesPersonEmail
FROM client c FROM client c
JOIN account.emailUser e ON e.userFk = c.salesPersonFk JOIN account.emailUser e ON e.userFk = c.salesPersonFk
LEFT JOIN workerDepartment wd ON wd.workerFk = c.salesPersonFk
LEFT JOIN department d ON d.id = wd.departmentFk
WHERE c.id = vClientFk; WHERE c.id = vClientFk;
SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ',
@ -199,20 +192,21 @@ BEGIN
SELECT COUNT(*) INTO vIsDuplicateMail SELECT COUNT(*) INTO vIsDuplicateMail
FROM mail FROM mail
WHERE receiver = vSalesPersonEmail WHERE receiver = vEmail
AND subject = vSubject; AND subject = vSubject;
IF NOT vIsDuplicateMail THEN IF NOT vIsDuplicateMail THEN
CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage); CALL mail_insert(vEmail, NULL, vSubject, vMessage);
END IF; END IF;
CALL ticket_setState(vNewTicket, 'FIXING'); CALL ticket_setState(vNewTicket, 'FIXING');
ELSE ELSE
CALL ticketCalculateClon(vNewTicket, vTicketFk); CALL ticketCalculateClon(vNewTicket, vTicketFk);
END IF; END IF;
END;
END LOOP; END LOOP;
CLOSE rsTicket; CLOSE vTickets;
DROP TEMPORARY TABLE IF EXISTS tmp.time, tmp.zoneGetLanded;
DROP TEMPORARY TABLE IF EXISTS
tmp.time,
tmp.zoneGetLanded;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -90,7 +90,7 @@ BEGIN
IF vIsTaxDataChecked THEN IF vIsTaxDataChecked THEN
CALL invoiceOut_newFromClient( CALL invoiceOut_newFromClient(
vClientFk, vClientFk,
(SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), (SELECT invoiceSerial(vClientFk, vCompanyFk, 'multiple')),
vShipped, vShipped,
vCompanyFk, vCompanyFk,
NULL, NULL,

View File

@ -56,13 +56,12 @@ BEGIN
FROM zone FROM zone
WHERE id = vZoneFk; WHERE id = vZoneFk;
CALL buyUltimate(vWarehouseFk, vShipped); CALL buy_getUltimate(NULL, vWarehouseFk, vShipped);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY (
SELECT SELECT vWarehouseFk warehouseFk,
vWarehouseFk AS warehouseFk, NULL available,
NULL AS available,
s.itemFk, s.itemFk,
bu.buyFk, bu.buyFk,
vZoneFk zoneFk vZoneFk zoneFk

View File

@ -1,5 +1,7 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_getProblems`(IN vIsTodayRelative tinyint(1)) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_getProblems`(
vIsTodayRelative tinyint(1)
)
BEGIN BEGIN
/** /**
* Calcula los problemas para un conjunto de tickets. * Calcula los problemas para un conjunto de tickets.

View File

@ -0,0 +1,49 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_mergeSales`(
vSelf INT
)
BEGIN
DECLARE vHasSalesToMerge BOOL;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
SELECT id INTO vSelf
FROM ticket
WHERE id = vSelf FOR UPDATE;
CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve
(PRIMARY KEY (id))
ENGINE = MEMORY
SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity
FROM sale s
JOIN item i ON i.id = s.itemFk
JOIN itemType it ON it.id = i.typeFk
WHERE s.ticketFk = vSelf
AND it.isMergeable
GROUP BY s.itemFk, s.price, s.discount
HAVING COUNT(*) > 1;
SELECT COUNT(*) INTO vHasSalesToMerge
FROM tSalesToPreserve;
IF vHasSalesToMerge THEN
UPDATE sale s
JOIN tSalesToPreserve stp ON stp.id = s.id
SET s.quantity = newQuantity;
DELETE s
FROM sale s
JOIN tSalesToPreserve stp ON stp.itemFk = s.itemFk
WHERE s.ticketFk = vSelf
AND s.id <> stp.id;
END IF;
COMMIT;
DROP TEMPORARY TABLE tSalesToPreserve;
END$$
DELIMITER ;

View File

@ -14,16 +14,28 @@ BEGIN
DECLARE vTicketFk INT; DECLARE vTicketFk INT;
DECLARE cTickets CURSOR FOR DECLARE cTickets CURSOR FOR
SELECT id FROM ticket SELECT DISTINCT t.id
WHERE refFk IS NULL FROM ticket t
AND ((vScope = 'client' AND clientFk = vId) LEFT JOIN tItems ti ON ti.id = t.id
OR (vScope = 'address' AND addressFk = vId)); WHERE t.refFk IS NULL
AND ((vScope = 'client' AND t.clientFk = vId)
OR (vScope = 'address' AND t.addressFk = vId)
OR (vScope = 'item' AND ti.id)
);
DECLARE CONTINUE HANDLER FOR NOT FOUND DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vDone = TRUE;
CREATE OR REPLACE TEMPORARY TABLE tItems
(PRIMARY KEY (id))
ENGINE = MEMORY
SELECT DISTINCT t.id
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN itemTaxCountry itc ON itc.itemFk = s.itemFk
WHERE t.refFk IS NULL
AND (vScope = 'item' AND itc.itemFk = vId);
OPEN cTickets; OPEN cTickets;
myLoop: LOOP myLoop: LOOP
SET vDone = FALSE; SET vDone = FALSE;
FETCH cTickets INTO vTicketFk; FETCH cTickets INTO vTicketFk;
@ -34,7 +46,8 @@ BEGIN
CALL ticket_recalc(vTicketFk, NULL); CALL ticket_recalc(vTicketFk, NULL);
END LOOP; END LOOP;
CLOSE cTickets; CLOSE cTickets;
DROP TEMPORARY TABLE tItems;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -12,24 +12,28 @@ BEGIN
*/ */
DECLARE vTicketFk INT; DECLARE vTicketFk INT;
DECLARE vHasProblem INT; DECLARE vHasProblem INT;
DECLARE vIsProblemCalcNeeded BOOL;
DECLARE vDone BOOL; DECLARE vDone BOOL;
DECLARE vTicketList CURSOR FOR SELECT ticketFk, hasProblem FROM tmp.ticket; DECLARE vTicketList CURSOR FOR
SELECT ticketFk, hasProblem, isProblemCalcNeeded
FROM tmp.ticket;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vTicketList; OPEN vTicketList;
l: LOOP l: LOOP
SET vDone = FALSE; SET vDone = FALSE;
FETCH vTicketList INTO vTicketFk, vHasProblem; FETCH vTicketList INTO vTicketFk, vHasProblem, vIsProblemCalcNeeded;
IF vDone THEN IF vDone THEN
LEAVE l; LEAVE l;
END IF; END IF;
UPDATE ticket UPDATE ticket
SET problem = CONCAT( SET problem = IF(vIsProblemCalcNeeded,
IF(vHasProblem, CONCAT(IF(vHasProblem,
CONCAT(problem, ',', vProblemCode), CONCAT(problem, ',', vProblemCode),
REPLACE(problem, vProblemCode , ''))) REPLACE(problem, vProblemCode , ''))),
NULL)
WHERE id = vTicketFk; WHERE id = vTicketFk;
END LOOP; END LOOP;
CLOSE vTicketList; CLOSE vTicketList;

View File

@ -0,0 +1,35 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setProblemRiskByClient`(
vClientFk INT
)
BEGIN
/**
* Updates future ticket risk for a client.
*
* @param vClientFk Id client
*/
DECLARE vDone INT DEFAULT FALSE;
DECLARE vTicketFk INT;
DECLARE vTickets CURSOR FOR
SELECT id
FROM ticket
WHERE clientFk = vClientFk
AND shipped >= util.VN_CURDATE()
AND refFk IS NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vTickets;
l: LOOP
SET vDone = FALSE;
FETCH vTickets INTO vTicketFk;
IF vDone THEN
LEAVE l;
END IF;
CALL vn.ticket_setProblemRisk(vTicketFk);
END LOOP;
CLOSE vTickets;
END$$
DELIMITER ;

View File

@ -16,7 +16,7 @@ BEGIN
FROM ticket FROM ticket
WHERE id = vSelf; WHERE id = vSelf;
CALL buyUltimate(vWarehouseFk, vDated); CALL buy_getUltimate(NULL, vWarehouseFk, vDated);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(INDEX(saleFk, isProblemCalcNeeded)) (INDEX(saleFk, isProblemCalcNeeded))

View File

@ -8,17 +8,27 @@ BEGIN
* *
* @param vSelf Id del ticket * @param vSelf Id del ticket
*/ */
DECLARE vTicketIsTooLittle BOOL;
SELECT ticket_isTooLittle(vSelf) INTO vTicketIsTooLittle;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
(INDEX(ticketFk, isProblemCalcNeeded)) (INDEX(ticketFk, isProblemCalcNeeded))
ENGINE = MEMORY ENGINE = MEMORY
SELECT vSelf ticketFk, WITH ticketData AS (
ticket_isTooLittle(vSelf) hasProblem, SELECT addressFk, DATE(shipped) dated
ticket_isProblemCalcNeeded(vSelf) isProblemCalcNeeded; FROM vn.ticket
WHERE id = vSelf
)
SELECT t.id ticketFk,
vTicketIsTooLittle hasProblem,
ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
FROM vn.ticket t
JOIN ticketData td ON td.addressFk = t.addressFk
WHERE t.shipped BETWEEN td.dated AND util.dayEnd(td.dated);
CALL ticket_setProblem('isTooLittle'); CALL ticket_setProblem('isTooLittle');
DROP TEMPORARY TABLE tmp.ticket; DROP TEMPORARY TABLE tmp.ticket;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -1,92 +1,81 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setRisk`( CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setRisk`(
vClientFk INT) vClientFk INT
)
BEGIN BEGIN
/** /**
* Update the risk for a client with pending tickets * Update the risk for a client with pending tickets.
* *
* @param vClientFk Id cliente * @param vClientFk Id cliente
*/ */
DECLARE vHasDebt BOOL; IF (SELECT COUNT(*) FROM client WHERE id = vClientFk AND typeFk = 'normal') THEN
DECLARE vStarted DATETIME;
SELECT COUNT(*) INTO vHasDebt
FROM `client`
WHERE id = vClientFk
AND typeFk = 'normal';
IF vHasDebt THEN
SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted
FROM clientConfig;
CREATE OR REPLACE TEMPORARY TABLE tTicketRisk CREATE OR REPLACE TEMPORARY TABLE tTicketRisk
(KEY (ticketFk)) (PRIMARY KEY (ticketFk))
ENGINE = MEMORY ENGINE = MEMORY
WITH ticket AS( WITH ticket AS (
SELECT id ticketFk, SELECT t.id ticketFk,
companyFk, t.companyFk,
DATE(shipped) dated, DATE(t.shipped) dated,
totalWithVat, t.totalWithVat,
ticket_isProblemCalcNeeded(id) isProblemCalcNeeded ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
FROM vn.ticket FROM vn.ticket t
WHERE clientFk = vClientFk JOIN vn.clientConfig cc
AND refFk IS NULL WHERE t.clientFk = vClientFk
AND NOT isDeleted AND t.refFk IS NULL
AND IFNULL(totalWithVat, 0) <> 0 AND NOT t.isDeleted
AND shipped > vStarted AND IFNULL(t.totalWithVat, 0) <> 0
), balance AS( AND t.shipped > (util.VN_CURDATE() - INTERVAL cc.riskScope MONTH)
SELECT SUM(amount)amount, companyFk ), uninvoiced AS (
FROM (
SELECT amount, companyFk
FROM vn.clientRisk
WHERE clientFk = vClientFk
UNION ALL
SELECT -(SUM(amount) / 100) amount, tm.companyFk
FROM hedera.tpvTransaction t
JOIN hedera.tpvMerchant tm ON t.id = t.merchantFk
WHERE clientFk = vClientFk
AND receiptFk IS NULL
AND status = 'ok'
) sub
WHERE companyFk
GROUP BY companyFk
), uninvoiced AS(
SELECT companyFk, dated, SUM(totalWithVat) amount SELECT companyFk, dated, SUM(totalWithVat) amount
FROM ticket FROM ticket
GROUP BY companyFk, dated GROUP BY companyFk, dated
), receipt AS( ), companies AS (
SELECT companyFk, DATE(payed) dated, SUM(amountPaid) amount SELECT DISTINCT companyFk FROM uninvoiced
FROM vn.receipt ), balance AS (
WHERE clientFk = vClientFk SELECT SUM(IFNULL(amount, 0))amount, companyFk
AND payed > util.VN_CURDATE() FROM (
GROUP BY companyFk, DATE(payed) SELECT cr.amount, c.companyFk
), risk AS( FROM companies c
LEFT JOIN vn.clientRisk cr ON cr.companyFk = c.companyFk
AND cr.clientFk = vClientFk
UNION ALL
SELECT -(SUM(t.amount) / 100) amount, c.companyFk
FROM companies c
LEFT JOIN hedera.tpvMerchant tm ON tm.companyFk = c.companyFk
LEFT JOIN hedera.tpvTransaction t ON t.merchantFk = tm.id
AND t.clientFk = vClientFk
AND t.receiptFk IS NULL
AND t.`status` = 'ok'
) sub
WHERE companyFk
GROUP BY companyFk
), receipt AS (
SELECT r.companyFk, DATE(r.payed) dated, SUM(r.amountPaid) amount
FROM vn.receipt r
JOIN companies c ON c.companyFk = r.companyFk
WHERE r.clientFk = vClientFk
AND r.payed > util.VN_CURDATE()
GROUP BY r.companyFk, DATE(r.payed)
), risk AS (
SELECT b.companyFk, SELECT b.companyFk,
ui.dated, ui.dated,
SUM(ui.amount) OVER (PARTITION BY b.companyFk ORDER BY ui.dated ) + SUM(ui.amount) OVER (PARTITION BY b.companyFk ORDER BY ui.dated) +
b.amount + b.amount +
SUM(IFNULL(r.amount, 0)) amount SUM(IFNULL(r.amount, 0)) amount
FROM balance b FROM balance b
JOIN uninvoiced ui ON ui.companyFk = b.companyFk JOIN uninvoiced ui ON ui.companyFk = b.companyFk
LEFT JOIN receipt r ON r.dated > ui.dated AND r.companyFk = ui.companyFk LEFT JOIN receipt r ON r.dated > ui.dated
AND r.companyFk = ui.companyFk
GROUP BY b.companyFk, ui.dated GROUP BY b.companyFk, ui.dated
) )
SELECT ti.ticketFk, r.amount, ti.isProblemCalcNeeded SELECT ti.ticketFk, r.amount, ti.isProblemCalcNeeded
FROM ticket ti FROM ticket ti
JOIN risk r ON r.dated = ti.dated AND r.companyFk = ti.companyFk; JOIN risk r ON r.dated = ti.dated
AND r.companyFk = ti.companyFk;
UPDATE ticket t UPDATE ticket t
JOIN tTicketRisk tr ON tr.ticketFk = t.id JOIN tTicketRisk tr ON tr.ticketFk = t.id
SET t.risk = tr.amount SET t.risk = IF(tr.isProblemCalcNeeded, tr.amount, NULL);
WHERE tr.isProblemCalcNeeded
ORDER BY t.id;
UPDATE ticket t
JOIN tTicketRisk tr ON tr.ticketFk = t.id
SET t.risk = NULL
WHERE tr.isProblemCalcNeeded
ORDER BY t.id;
DROP TEMPORARY TABLE tTicketRisk; DROP TEMPORARY TABLE tTicketRisk;
END IF; END IF;

View File

@ -0,0 +1,24 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setVolume`(
vSelf INT
)
BEGIN
/**
* Update the volume ticket
*
* @param vSelf Ticket id
*/
DECLARE vVolume DECIMAL(10,6);
SELECT SUM(s.quantity * ic.cm3delivery / 1000000) INTO vVolume
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
JOIN itemCost ic ON ic.itemFk = s.itemFk
AND ic.warehouseFk = t.warehouseFk
WHERE t.id = vSelf;
UPDATE ticket
SET volume = vVolume
WHERE id = vSelf;
END$$
DELIMITER ;

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